Test name | Executions per second |
---|---|
trim and always replace | 2453.7 Ops/sec |
trim and conditionally replace | 2604.8 Ops/sec |
trim and conditionally replace with if | 2607.7 Ops/sec |
always replace and trim | 2255.7 Ops/sec |
conditionally trim and conditionally replace | 2641.4 Ops/sec |
const arr = []
for(let i = 1; i < 1000; i++) {
arr.push(' '.repeat(i))
}
for(let i = 1; i < 100; i++) {
arr.push('');
arr.push(' text '.repeat(i))
}
const run = (fn) => {
const result = []
for(const val of arr) {
result.push(fn(val));
}
return result
}
run((val) => val.trim().replace(/\s+/g, ' '))
run((val) => {
const trimmed = val.trim();
return trimmed && trimmed.replace(/\s+/g, ' ');
})
run((val) => {
const trimmed = val.trim();
if (trimmed === '') {
return '';
} else {
return trimmed.replace(/\s+/g, ' ');
}
})
run((val) => val.replace(/\s+/g, ' ').trim())
run((val) => {
if(val === '') {
return val;
}
const trimmed = val.trim();
if (trimmed === '') {
return trimmed;
} else {
return trimmed.replace(/\s+/g, ' ');
}
})