@rmurphey-foo-foo-foo

JavaScript performance comparison

Revision 14 of this test case created by Alex Sexton

Info

Testing performance of different implementations for @rmurpheys challenge for creating and array of tripled string values.

http://gist.github.com/576723

Who said JavaScript OCD?

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
  // 5: given the following array, create an array that contains the contents of
  // each array item repeated three times, with a space between each item. so,
  // for example, if an array item is 'foo' then the new array should contain an
  // array item 'foo foo foo'. (you can assume the library of your choice is
  // available)
  var myArray = ['foo', 'bar', 'baz', 'bat', 'batty', 'buzzy', 'booz'];
</script>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
for loop
var loopy = [];
for (var i = 0, j = myArray.length; i < j; i++) {
 loopy.push([myArray[i], myArray[i], myArray[i]].join(' '));
}
pending…
ES5 - forEach
var es5 = [];

function triple(item) {
 es5.push([item, item, item].join(' '));
}
myArray.forEach(triple);
pending…
ES5 - map
function triple(item) {
 return [item, item, item].join(' ');
}
var es5 = myArray.map(triple);
pending…
jQuery.each
var results = [];
$.each(myArray, function(index, item) {
 results.push([item, item, item].join(' '));
});
pending…
for loop, regexp concat
var results = [];
var re = /(.*)/;
for (var i = 0, j = myArray.length; i < j; i++) {
 results.push(myArray[i].replace(re, "$1 $1 $1"));
}
pending…
reverse while (with concat)
var i = myArray.length,
    result = new Array(i);

while (i--) {
 var item = myArray[i];
 result[i] = item + " " + item + " " + item;
}
pending…
reverse while (with join)
var i = myArray.length,
    result = new Array(i);

while (i--) {
 var item = myArray[i];
 result[i] = [item, item, item].join(" ");
}
pending…
fast for
var l = myArray.length,
    result = new Array(l);
for (var i = 0; i < l; i++) {
 var item = myArray[i];
 result[i] = item + " " + item + " " + item;
}
pending…
Manual
var result = ['foo foo foo', 'bar bar bar', 'baz baz baz', 'bat bat bat', 'batty batty batty', 'buzzy buzzy buzzy', 'booz booz booz'];
pending…
ES5 - map (not really the slowest of them all!)
function triple(item) {
 return Array(4).join(' ' + item).substr(1);
}
var es5 = myArray.map(triple);
pending…
ES5 - map (updated to be slower)
function triple(item) {
 return $.trim(Array(4).join(' ' + item));
}
var es5 = myArray.map(triple);
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment