-
-
Save saabi/2650287 to your computer and use it in GitHub Desktop.
Benchmark str concatenation
This file contains hidden or 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
var Benchmark = require('benchmark'); | |
var suite = new Benchmark.Suite, | |
a, b; | |
global.str = 'TextTextTextTextTextTextTextTextTextTextTextTextTextTextText\n'; | |
global.str2 = 'TextTextTextTextTextTextTextTextTextTextTextTextTextTextText\\n'; | |
var statement = 'var str = global.str;\nvar s='; | |
for (i=0; i<100; i++) | |
if (i!=99) | |
statement += 'str+'; | |
else | |
statement += 'str;'; | |
var fn = new Function('', statement); | |
var statement2 = 'var s='; | |
for (i=0; i<100; i++) | |
if (i!=99) | |
statement2 += '"'+global.str2+'"+'; | |
else | |
statement2 += '"'+global.str2+'";'; | |
var fn2 = new Function('', statement2); | |
var statement3 = 'var str = global.str;\nvar s='; | |
for (i=0; i<100; i++) | |
if (i!=99 && i%2) | |
statement3 += '"'+global.str2+'"+'; | |
else if (i%2==0) | |
statement3 += 'str+'; | |
else | |
statement3 += '"'+global.str2+'";'; | |
var fn3 = new Function('', statement3); | |
suite | |
.add('push', function () { | |
a = []; | |
var str = global.str; | |
for (var i = 0; i < 100; i++) | |
a.push(str); | |
b = a.join(); | |
}) | |
.add('add', function () { | |
b = ''; | |
var str = global.str; | |
for (var i = 0; i < 100; i++) | |
b += str; | |
}) | |
.add('concat', fn) | |
.add('litconcat', fn2) | |
.add('mixedconcat', fn3) | |
.on('cycle', function (event, bench) { | |
console.log(bench.toString()); | |
}) | |
.on('complete', function () { | |
console.log('Fastest is ' + this.filter('fastest').pluck('name')); | |
}) | |
.run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
push x 293,764 ops/sec ±0.80% (54 runs sampled)
add x 644,289 ops/sec ±4.85% (44 runs sampled)
concat x 878,138 ops/sec ±3.62% (47 runs sampled)
litconcat x 7,195,488 ops/sec ±254.21% (6 runs sampled)
mixedconcat x 880,040 ops/sec ±3.48% (48 runs sampled)
Fastest is litconcat