DEV Community

101samovar
101samovar

Posted on

How fast your code is?

Suppose we have two code snippets that do the same thing.
How to check which one is faster?
Let we have an array of numbers.
And we have to do mathematical evaluation for each item.
There is more than one way to do it.
One way is to use a map method and an arrow function.
The other way is to use a for loop and a push method.
So we have two code snippets for one task.
Which one is faster?
Let’s define the benchmark function.
Function has one parameter: code snippet.
In that function we will repeat code snippet execution multiple times.

const array = [1, 2, 3, 4, 5, 6];
const snippetA = () => {array.map(x => Math.sin(x))};
const snippetB = () => {
    let result = [];
    for (let i = 0; i < array.length; i++) {
        result.push(Math.sin(array[i]));
    }
    return result;
};

const benchmark = snippet => {
    const count = 1000000;
    let start = new Date();
    for (let i = 0; i < count; i++) {
        snippet();
    }
    return new Date() - start;
};

console.log('map: ', benchmark(snippetA));
console.log('for: ', benchmark(snippetB));

Enter fullscreen mode Exit fullscreen mode

And we check how much time it requires.
The less time period the faster the code snippet.
OK.
Let’s check it out.
101samovar
The snippet A with a map method.
And the snippet B with a for loop.
The snippet B has required less time.
The for snippet is faster.


I hope you found this article useful, if you need any help please let me know in the comment section.

👋 See you next time. Have a nice day!

Subscribe to our channel:
https://www.youtube.com/c/Samovar101

Discussion (2)

Collapse
totally_chase profile image
Phantz • Edited on

Results from a micro-bench like this may very well be misleading in the context of a highly optimizing compiler like V8. Hint: The snippet function call ignores its result.

The truth is, benchmarking is hard. Micro-benchmarking is harder and often extremely misleading. Here's a great talk from a V8 engineer on this topic. Hopefully it'll open some people's eyes.

On another note, in practical code, the difference in performance, between .map and a regular for..of loop, is insignificant (reasons: map fusion, the inline cache and inlining in general, efficient iterator protocols on certain collections). Choose whichever makes the intent immediately clear.

  • Doing a singular, pure mapping operation? Use .map - it's immediately clear to the programmer without having to checkout the condition, and body of a loop.
  • Doing one or more effect-ful looping operations? Use a for loop.
Collapse
101samovar profile image
101samovar Author

Thank you for your comment and for the link to Vyacheslav Egorov's instructive presentation.
However, there is nothing wrong with wanting to measure the speed of your code. Yes, taking into account that in some cases the benchmark results need to be treated with increased attention.