Skip to content

Instantly share code, notes, and snippets.

@Sannis
Created March 18, 2010 22:56
Show Gist options
  • Save Sannis/337019 to your computer and use it in GitHub Desktop.
Save Sannis/337019 to your computer and use it in GitHub Desktop.
node_string_concat_vs_array_join_benchmark.js
var
sys = require('sys'),
chunk = "1234567890htcje,stdl",
chunk_length = parseInt(process.ARGV[2]),
count = parseInt(process.ARGV[3]),
i;
function doBenchmark(title, execute_function) {
var
start,
finish,
data;
start = new Date();
execute_function();
finish = new Date();
sys.puts(title + ": " + Math.round(finish.valueOf() - start.valueOf()) + "ms");
}
function humanSize(size) {
var suffix = "";
if (size >= 1024) {
suffix = "Kb";
size /= 1024;
}
if (size >= 1024) {
suffix = "Mb";
size /= 1024;
}
return size + suffix;
}
// Generate chunk
sys.puts("Generate chunk...");
while (chunk.length < chunk_length) {
chunk += chunk;
}
chunk = chunk.substr(0, chunk_length);
sys.puts("Chunk length: " + chunk_length + " bytes = " + humanSize(chunk_length));
sys.puts("Chunks count: " + count);
sys.puts("Content length: " + (chunk_length * count) + " bytes = " + humanSize(chunk_length * count));
// Benchmark 1: String concatenation
doBenchmark("String concatenation", function () {
var content = "", i;
for (i = 0; i < count; i += 1) {
content += chunk;
}
content = content;
});
// Benchmark 2: Array join
doBenchmark("Array join", function () {
var content = [], i;
for (i = 0; i < count; i += 1) {
content.push(chunk);
}
content = content.join('');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment