Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.prototype vs [] perf

Quick question that I haven't really had a chance to look into. Which is more performant when used in a call/apply sort of context: Array.prototype vs []?

e.g.:

function test1() {
    return Array.prototype.splice.apply(arguments, [1, 2]);
}

test1([1,2,3,4,5,6,7,8,9]);

function test2() {
    return [].splice.apply(arguments, [1, 2]);
}

test1([1,2,3,4,5,6,7,8,9]);

My thoughts: I would assume the Array.prototype way is more performant because a prototype function can be reused and no literal need be created. Not really sure though.

Using JSPerf (with chrome) it looks like the Array.prototype is indeed slightly more performant:

http://jsperf.com/array-perf-prototype-vs-literal

like image 596
Peter Dev Avatar asked Jul 20 '12 10:07

Peter Dev


1 Answers

It depends on the browser running it. In chrome it seems .prototype is faster, firefox shows no difference between the two although generally performs slower than chrome. IE9 shows a big speed increase for .prototype but is the slowest browser by far.

However, this sort of optimization is so small that one could argue the time saved is offset against the extra bytes required to read the code. I digress though, If these are the biggest performance issues your coming against then you really don't have any problems with optimization!

EDIT:

I added an extra test here where I used the array passed into the function to call the splice function which showed up as faster than both in both IE, Chrome and Firefox. My conclusion, if you already have the array handy, use it, else use the prototype.

like image 165
Dpolehonski Avatar answered Sep 22 '22 02:09

Dpolehonski