Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is array.map(String.fromCharCode) so slow?

It started out when I read Guido van Rossum's essay An Optimization Anecdote.

Deciding to try the same thing in JavaScript, I timed the following:

numbers.map(function(x){ return String.fromCharCode(x); });

This was pretty fast already, but why not eliminate the anonymous function completely and pass String.fromCharCode directly to map():

numbers.map(String.fromCharCode);

I timed it and... ...this was ~100 times slower than the previous version. How come?

Somehow passing this native function directly to Array.map() is way slower than wrapping it inside another function and passing that to Array.map().

  • It's not browser specific: tested in Chrome, Firefox and Opera.

  • It's not specific to map(): tried forEach(), which behaved similarly.

  • It's not specific to built-in functions: tried Math.round() and Math.sin() - with these the results were as one would expect: passing the function to Array.map() directly was a little bit faster than using intermediate anonymous function.

It seems the problem is with String.fromCharCode specifically.

What's going on here?

PS. Originally posed this question in Hacker News thread, but since the related article is about Python, I thought it would get more exposure to JavaScript devs when posted here. Sorry for cross-posting.

like image 296
Rene Saarsoo Avatar asked Nov 02 '10 13:11

Rene Saarsoo


1 Answers

Found the solution by myself.

The problem is that String.fromCharCode() takes multiple arguments and Array.map() also passes multiple arguments to the callback. Therefore the code:

numbers.map(String.fromCharCode);

Is actually equivalent of:

numbers.map(function(x, y, z){ return String.fromCharCode(x, y, z); });

From which it is quite apparent why it's so slow. Additionally it's buggy too.

like image 180
Rene Saarsoo Avatar answered Nov 12 '22 20:11

Rene Saarsoo