Small Array -> operation -> to Array (v3)

Revision 3 of this benchmark created on


Setup

let str = ["a", "b", "c", "d", "e", "f", "g", "h"];

Test runner

Ready to run.

Testing in
TestOps/sec
String concatenation + split
let res = "";
for (let i = 0; i < str.length; i++) {
    if (str[i] == "a") continue;
    res += str[i];
}
return res.split();
ready
String concatenation with template literal + split
let res = "";
for (let i = 0; i < str.length; i++) {
	if (str[i] == "a") continue;
    res = `${res}${str[i]}`;
}
return res.split();
ready
Pushing elements in array. Traditional for loop
let res = [];
for (let i = 0; i < str.length; i++) {
    if (str[i] == "a") continue;
    res.push(str[i]);
}
return res;
ready
Define array with string size
const arr = new Array(str.length);

let count = 0;
for (let i = 0; i < str.length; i++) {
  if (str[i] == "a") continue;
  arr[count++] = str[i];
}
arr.length = count;
return arr;
ready
Define array by counting the output length
let validCount = 0;
for (let i = 0; i < str.length; i++) {
  if (str[i] !== "a") validCount++;
}

const arr = new Array(validCount);

let writeIndex = 0;
for (let i = 0; i < str.length; i++) {
	if (str[i] == "a") continue;
	arr[writeIndex++] = str[i];
}

return arr;
ready
for of loop
let arr = [];
for (let letter of str) {
  if (letter !== "a") {
    arr.push(letter);
  }
}
return arr;
ready
Array from + filter
return Array.from(str).filter(letter => letter !== "a");
ready
Spread operator + filter
return [...str].filter(letter => letter !== "a");
ready
Regex
return str.match(/[^a]/g) || [];
ready

Revisions

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