I thought the fastest way to reverse a string is using just a for loop. but after measuring execution time, It turns out that Convert this to an array, reversing it then join it is faster which is not reasonable as far as I know.
This is how I measured
const { PerformanceObserver, performance } = require("perf_hooks");
var t0 = performance.now();
var reverse = function (x) {
x = x.toString();
result = "";
for (let i = x.length - 1; i >= 0; i--) { // O(n)
result += x[i];
}
return;
};
reverse(1534236469);
var t1 = performance.now();
console.log("took " + (t1 - t0) + " milliseconds.");
var t3 = performance.now();
var reverse = function (x) {
const xStrArr = Math.abs(x).toString().split(""); O(n)
const reversStr = xStrArr.reverse().join(""); O(2n)
return;
};
reverse(1534236469);
var t4 = performance.now();
console.log("took " + (t4 - t3) + " milliseconds.");
How could second execution, O(3n) be faster than O(n)? Can someone explain to me?