String concatenation "+=" vs array.join

Benchmark created on


Description

Measuring iterative concatenation of multiple short strings into one large one

Preparation HTML

<table id="tab">
<thead>
	<th>Day</th>
	<th>Change</th>
	<th>Total</th>
	<th>Expected</th>
	<th>Remaining</th>
</thead>
<tbody>
</tbody>
</table>

Setup

const ROWS = 10000;
let tb = document.querySelector("tbody");

for (let idx = 0; idx < ROWS; idx++) {
	let row = gen_trow(idx + 1);
	tb.appendChild(row);
}

function gen_trow(day_number) {
	let row_ele = document.createElement("trow");
	let v = gen_values(day_number);
	for (let n of v) {
		let cell = document.createElement("td");
		cell.textContent = n;
		row_ele.appendChild(cell);
	}
	return row_ele;
}

function gen_values(n) {
	let noise_factor = Math.random() * 0.05;
	let base_value = Math.sin(n/10);
	
	return [n + base_value, noise_factor, 100 * n * (1 + noise_factor), base_value * n];
}

Teardown

//let tb = document.querySelector("tbody");

while (tb.firstChild) {
	tb.removeChild(tb.lastChild);
}

Test runner

Ready to run.

Testing in
TestOps/sec
Pure Array.join
let header = document.querySelector("thead");
let rows = document.querySelectorAll("trow");

function extract() {
	let buffer = [];
	for (let a = 0; a < header.childNodes.length; a++) {
		if (a != 0) buffer.push(",");
		buffer.push(header.childNodes[a].textContent);
		
	}
	buffer.push("\n");
	for(let r of rows) {
		for (let a = 0; a < r.childNodes.length; a++) {
			if (a != 0) buffer.push(",");
			buffer.push(r.childNodes[a].textContent);
		}
		buffer.push("\n");
	}
	
	return buffer.join("");
}

extract();
ready
Pure += String
let header = document.querySelector("thead");
let rows = document.querySelectorAll("trow");

function extract() {
	let buffer = "";
	for (let a = 0; a < header.childNodes.length; a++) {
		if (a != 0) buffer += ",";
		buffer += header.childNodes[a].textContent;
		
	}
	buffer += "\n";
	for(let r of rows) {
		for (let a = 0; a < r.childNodes.length; a++) {
			if (a != 0) buffer += ",";
			buffer += r.childNodes[a].textContent;
		}
		buffer += "\n";
	}
	
	return buffer;
}

extract()
ready
Mixed (+cells, join newlines)
let header = document.querySelector("thead");
let rows = document.querySelectorAll("trow");

function extract() {
	let buffer = "";
	for (let a = 0; a < header.childNodes.length; a++) {
		if (a != 0) buffer += ",";
		buffer += header.childNodes[a].textContent;
		
	}
	buffer += "\n";
	for(let r of rows) {
		for (let a = 0; a < r.childNodes.length; a++) {
			if (a != 0) buffer += ",";
			buffer += r.childNodes[a].textContent;
		}
		buffer += "\n";
	}
	
	return buffer;
}

extract()
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.