Rene Saarsoo
Rene Saarsoo

Reputation: 13917

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 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.

Upvotes: 7

Views: 1313

Answers (1)

Rene Saarsoo
Rene Saarsoo

Reputation: 13917

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.

Upvotes: 7

Related Questions