Javascript Charat() Runtime
What is the runtime complexity of the charAt() function in JavaScript with respect to the string length? Is it defined in EcmaScript (I failed to find it)? If not, what's the behav
Solution 1:
Here is a small experiment: I generate texts of different lengths and perform charAt
a million times.
functionrepeat(text, n) {
const randomPositions = [];
for (let i = 0; i < n; i++) {
randomPositions.push(Math.floor(Math.random() * text.length));
}
const t0 = performance.now();
for (let pos of randomPositions) {
text.charAt(pos);
}
console.log("Elapsed time: " + (performance.now() - t0) + " ms")
}
const characters ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
// Thanks https://www.programiz.com/javascript/examples/generate-random-stringsfunctiongenerateString(length) {
let result = '';
const charactersLength = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
[10**2, 10**3, 10**4, 10**5, 10**6, 10**7].forEach(l =>repeat(generateString(l), 10000000));
I run it in Chrome 91, Firefox 89 and Safari 14.
Results:
In Chrome and Firefox, the needed time does not seem to correlate very strongly with the text length indicating O(1). Some example times:
# Chrome:Elapsed time:37.40000003576279msElapsed time:39.5msElapsed time:38.30000001192093msElapsed time:39.40000003576279msElapsed time:46.39999997615814msElapsed time:45.89999997615814ms# FirefoxElapsed time:255msElapsed time:224msElapsed time:269msElapsed time:227msElapsed time:424msElapsed time:393ms
In Safari, the needed time goes up:
Elapsedtime: 94.00000000005821msElapsedtime: 83.0000000000291msElapsedtime: 93msElapsedtime: 128msElapsedtime: 294msElapsedtime: 571ms
Did I miss an important factor? Please let me know!
Post a Comment for "Javascript Charat() Runtime"