Created
August 7, 2008 13:18
-
-
Save JosephPecoraro/4397 to your computer and use it in GitHub Desktop.
Benchmarking String Concatenation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Benchmarking String Concatenation Comparing | |
// 1. Array.join | |
// 2. String concatenation with '+' | |
// Test Functions | |
function test_join(content) { return ['output.push(', content, ');'].join(''); }; | |
function test_str_concat(content) { return 'output.push(' + content + ');'; }; | |
// Test Strings | |
var SHORT_STRING = 'test'; | |
var LONG_STRING = SHORT_STRING; | |
for (var i=0; i<1e3; ++i) LONG_STRING += SHORT_STRING; | |
// Verify they do the same thing | |
var s1 = test_join(SHORT_STRING); | |
var s2 = test_str_concat(SHORT_STRING); | |
console.log( s1 ); | |
console.log( s2 ); | |
if ( s1 != s2 ) console.log('Different Outputs.'); | |
// ----- | |
// Test 1. Array.join on a short string | |
// ----- | |
(function(){ | |
var s = (new Date()).getTime(); | |
for (var i=0; i<1e5; i++) { test_join(SHORT_STRING); } | |
var e = (new Date()).getTime(); | |
console.log( (e-s) + 'ms' ); | |
})(); | |
// ----- | |
// Test 2. Array.join on a long string | |
// ----- | |
(function(){ | |
var s = (new Date()).getTime(); | |
for (var i=0; i<1e5; i++) { test_join(LONG_STRING); } | |
var e = (new Date()).getTime(); | |
console.log( (e-s) + 'ms' ); | |
})(); | |
// ----- | |
// Test 3. String concat on a short string | |
// ----- | |
(function(){ | |
var s = (new Date()).getTime(); | |
for (var i=0; i<1e5; i++) { test_str_concat(SHORT_STRING); } | |
var e = (new Date()).getTime(); | |
console.log( (e-s) + 'ms' ); | |
})(); | |
// ----- | |
// Test 4. String concat on a long string | |
// ----- | |
(function(){ | |
var s = (new Date()).getTime(); | |
for (var i=0; i<1e5; i++) { test_str_concat(LONG_STRING); } | |
var e = (new Date()).getTime(); | |
console.log( (e-s) + 'ms' ); | |
})(); | |
// ----- | |
// Results on my Leopard Mac with Firefox 3 | |
// ----- | |
// Tests | Average | |
// ---------------------------------------------- | |
// 1. 651ms, 595ms, 590ms, 592ms => 607.00 | |
// 2. 1204ms, 1086ms, 1083ms, 1068ms => 1110.25 | |
// 3. 146ms, 136ms, 134ms, 134ms => 137.50 | |
// 4. 1008ms, 969ms, 962ms, 981ms => 980.00 | |
// ----- | |
// Notes | |
// ----- | |
// | |
// 1. I don't know the typical usage for the function, but | |
// it seems like for short stings its faster to just '+' | |
// 2. My tests ran 1e5 times, thats 1 million times, and the | |
// results are low enough that you probably won't see | |
// any performance difference at a low number of | |
// invokations. [See #1] | |
// | |
// - Joseph Pecoraro | |
// |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment