In one of the example pieces of code in the Programming Fundamental Series I show you how you create a function that will obtain the absolute value of any given number. The function that I create is a simple one to follow and it illustrates and important part of functions.
This got me thinking though.
How does the runtime implement this feature? I’m sure they are using more efficient and well-tested code than what I created.
Right?
Here is the code from the example:
The first step that I tried to do was to just check the Math.abs
function with node. Here is what I get back.
console.log(Math.abs.toString());
The Output
function abs() { [native code] }
Not useful at all.
I started to look around and I found Code Search a tool that allows you to search the code repository.
I found the function that I was looking for:
Pretty Cool! Now you can see how the library works. This is really useful if you dream of creating your own library in the near feature which I hope you do!
As you can see the code from the Chromium runtime is not that more different than what I created. Yes, it’s using the ?
ternary operator to accomplish the branching but other than that everything looks about the same.
One small change that I noticed was the -
subtraction over *
multiplication. I’m wondering if this is a small performance improvement since multiplying is a more costly operation compared to subtraction than multiplication.
Let me know below in the comments what you think.
Talk to you next time,
Rick H.
I always had a passion for the field of STEM (Science, Technology, Engineering, and Math) and I knew I wanted to do something to make a difference in the world. I just didn’t know where to start. I was an immigrant in a new country, grew up in a tough environment, and wasn’t sure how… Read More