Are anonymous functions optimized in node.js

44 Views Asked by At

Let's take this stupid piece of code as an example

for (let i = 0; i < 10; i++) {
  console.log(
    (function (x) {
      if (x % 2) {
        return 'even';
      } else {
        return 'odd';
      }
    })(i)
  );
}

Basically, we have an anonymous function that is called multiple times inside a loop, or maybe inside another function. I wonder if it is recreated on every iteration of the cycle or is it optimized somehow? I would appreciate if you could give me a hint on how to find this kind of things on my own. Thanks!

1

There are 1 best solutions below

1
Alexander Nenashev On BEST ANSWER

Seems 2.5x slower in Chrome, but the same in Firefox. Seems Firefox was able to inline it. Though an arrow function is slower in Firefox. I guess maybe because of binding this and arguments to the outer scope, but who knows...

` Chrome/122
-------------------------------------------------
outline       1.00x | x100000 232 235 245 245 251
inline        2.48x | x100000 576 584 591 593 594
inline arrow  2.52x | x100000 584 585 588 588 607
-------------------------------------------------
https://github.com/silentmantra/benchmark `
` Firefox/123
-------------------------------------------------
outline       1.00x | x100000 469 479 482 484 500
inline        1.02x | x100000 477 494 510 525 525
inline arrow  1.12x | x100000 525 593 601 616 621
-------------------------------------------------
https://github.com/silentmantra/benchmark `

// @benchmark inline
for (let i = 0; i < 10000; i++) {
    (function (x) {
      if (x % 2) {
        return 'even';
      } else {
        return 'odd';
      }
    })(i)
}

// @benchmark inline arrow
for (let i = 0; i < 10000; i++) {
    (x => x % 2 ? 'even' : 'odd')(i);
}

// @benchmark outline
const fn = function (x) {
      if (x % 2) {
        return 'even';
      } else {
        return 'odd';
      }
    };
    
// @run

for (let i = 0; i < 10000; i++) {
  fn(i)
}

/*@end*/eval(atob('e2xldCBlPWRvY3VtZW50LmJvZHkucXVlcnlTZWxlY3Rvcigic2NyaXB0Iik7aWYoIWUubWF0Y2hlcygiW2JlbmNobWFya10iKSl7bGV0IHQ9ZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgic2NyaXB0Iik7dC5zcmM9Imh0dHBzOi8vY2RuLmpzZGVsaXZyLm5ldC9naC9zaWxlbnRtYW50cmEvYmVuY2htYXJrL2xvYWRlci5qcyIsdC5kZWZlcj0hMCxkb2N1bWVudC5oZWFkLmFwcGVuZENoaWxkKHQpfX0='));