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?
.reverse()is a native method that can be much more highly optimized (perhaps even entirely native code) than constructing your own Javascript to reverse the string manually.Onotation, you should know thatO(n) === O(3n), so beyond having linear time complexity, either could be faster.result += x[i];inside a loop is a sub-optimal way to construct a string as it keeps having to grow the memory required and copy the string to the new memory location.