test splitByFirstComma

Benchmark created on


Description

testing 2 approaches:

  • one that finds the position of the first comma and uses substr
  • the other that uses split(",") and joins the "rest"

the functon should always returns an empty string for the secnd returned value.

Preparation HTML

<script>
function splitByFirstComma1(str) {
	const firstCommaPos = str.indexOf(',');
	if (firstCommaPos === -1) {
		return [str, ""];
	}
	const firstPart = str.substr(0, firstCommaPos);
	const lastPart = str.substr(firstCommaPos+1);
	console.log(">", firstPart, lastPart);
	return [firstPart, lastPart];
}

function splitByFirstComma2(str) {
	const [firstPart, ...rest] = str.split(",");
	return [firstPart, rest.join(",")]
}
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
split1 no comma
splitByFirstComma1("coucou");
ready
split1 with 2 parts
splitByFirstComma1("coucou,poupou");
ready
split1 lot of commas
splitByFirstComma1("coucou,poupou,coucou,poupou,coucou,poupou");
ready
split2 with no comma
splitByFirstComma2("coucou");
ready
split2 with 2 parts
splitByFirstComma2("coucou,poupou");
ready
split2 lot of commas
splitByFirstComma2("coucou,poupou,coucou,poupou,coucou,poupou");
ready

Revisions

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