Created
April 20, 2012 13:08
-
-
Save chowey/2428348 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; | |
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(); |
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
Results:
Adding is faster by about 30% for this use case (equivalent to concatenating 100 lines of something).