function format1(inputString) {
// String slicing approach
return inputString.slice(0, 4) + 'Y' +
inputString.slice(4, 6) + 'M' +
inputString.slice(6, 8) + 'D ' +
inputString.slice(8, 10) + ':' +
inputString.slice(10, 12) + ':' +
inputString.slice(12, 14);
}
function format2(inputString) {
// String slicing + Array joining approach
const [Y, M, D, h, m, s] = [
inputString.slice(0, 4),
inputString.slice(4, 6),
inputString.slice(6, 8),
inputString.slice(8, 10),
inputString.slice(10, 12),
inputString.slice(12, 14)
];
return `${Y}Y${M}M${D}D ${h}:${m}:${s}`;
}
function format3(inputString) {
// Regex approach
return inputString.replace(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/, '$1Y$2M$3D $4:$5:$6');
}
function benchmark(format, times = 1000000) {
return function (inputString) {
let result;
const start = performance.now();
for (let i = 0; i < times; i++) {
result = format(inputString);
}
const end = performance.now();
const time = end - start;
const avgTime = time / times;
return [avgTime, result];
}
}
function main() {
const inputString = '20220420201001';
const [time1, result1] = benchmark(format1)(inputString);
const [time2, result2] = benchmark(format2)(inputString);
const [time3, result3] = benchmark(format3)(inputString);
console.log(`format1 took: ${time1}ms in average,\nresult: ${result1}\n`);
console.log(`format2 took: ${time2}ms in average,\nresult: ${result2}\n`);
console.log(`format3 took: ${time3}ms in average,\nresult: ${result3}\n`);
}
main();
I can come up with 3 solutions here:
Straightforward but might be a bit verbose
It could be deem advanced version of 2. String slicing approach
, which is more clean and readable
Concise but introduced overhead. (Pattern Matching is computationally intensive work. Many regex engines use backtracking to handle certain types of patterns.)
2. String slicing + Array joining approach
is generally preferred for readability and efficiency in most scenarios, as it avoids the regex overhead and reduces the complexity of multiple string concats.
performance.now()
is preferred over other timing methods like Date.now()
for benchmarking because of its higher precision and accuracy.
- Precision:
Date.now()
provides timestamps with millisecond precision - Accuracy:
Date.now()
can be affected by system clock adjustments
- Deduct the noise
- Provides a statistically significant result
- Consider Warm-Up Effects ( JavaScript engines often use JIT compilation, where the performance of the code can change after it has been run a few times due to optimizations.)