Skip to content

Instantly share code, notes, and snippets.

@chowey
Created April 20, 2012 13:08
Show Gist options
  • Save chowey/2428348 to your computer and use it in GitHub Desktop.
Save chowey/2428348 to your computer and use it in GitHub Desktop.
Benchmark str concatenation
var Benchmark = require('benchmark');
var suite = new Benchmark.Suite,
a, b;
suite
.add('push', function () {
a = [];
for (var i = 0; i < 100; i++)
a.push('Text\n');
b = a.join();
})
.add('add', function () {
b = '';
for (var i = 0; i < 100; i++)
b += 'Text\n';
})
.on('cycle', function (event, bench) {
console.log(bench.toString());
})
.on('complete', function () {
console.log('Fastest is ' + this.filter('fastest').pluck('name'));
})
.run();
@chowey
Copy link
Author

chowey commented Apr 20, 2012

Results:

>node bench
push x 638,572 ops/sec ±1.24% (55 runs sampled)
add x 842,122 ops/sec ±3.33% (48 runs sampled)
Fastest is add

Adding is faster by about 30% for this use case (equivalent to concatenating 100 lines of something).

@chowey
Copy link
Author

chowey commented Apr 20, 2012

Speed improvement is better when concatenating longer strings:

str = 'TextTextTextTextTextTextTextTextTextTextTextTextTextTextText\n';

gives

>node bench
push x 405,356 ops/sec ±0.95% (55 runs sampled)
add x 885,074 ops/sec ±0.84% (61 runs sampled)
Fastest is add

which is now better than 2x faster.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment