function validCharForL(s){
const n='"*/:<>?\\|';
let r="";
for(let i=0,l=s.length;i<l;i++)
r+=n.includes(s[i])?String.fromCharCode(s.charCodeAt(i)+65248):s[i];
return r
};
function validCharForOf(s){
const n='"*/:<>?\\|';
let r="";
for(let c of s)
r+=n.includes(c)?String.fromCharCode(c.charCodeAt()+65248):c;
return r
};
for (let i = 0; i < 1000; i++)
validCharForL("1234*/:<abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234");
for (let i = 0; i < 1000; i++)
validCharForOf("1234*/:<abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234abcd1234");
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
For Loop | |
For Of |
Test name | Executions per second |
---|---|
For Loop | 322.7 Ops/sec |
For Of | 288.4 Ops/sec |
This benchmark compares the performance of two methods for iterating over a string in JavaScript: a traditional for
loop and a for...of
loop.
Here's what each method does:
validCharForL(s)
(using a for
loop):
n
containing characters considered invalid for Windows and Linux file paths.s
using a for
loop, accessing each character by its index (i
).n
string (using includes
).r
.validCharForOf(s)
(using a for...of
loop):
for
loop version.c
) in the input string s
directly using a for...of
loop. c
:c
is present in the n
string (using includes
).r
.Comparison:
Approach | for loop |
for...of loop |
---|---|---|
Syntax | More verbose; requires explicit index management. | Simpler and more concise; iterates directly over values. |
Performance | Can be slightly faster in some cases due to potentially lower overhead for accessing elements by index. However, the difference is often negligible. | Generally considered easier to read and maintain, and often performs comparably to for loops in modern JavaScript engines. |
Alternatives:
.map()
and .forEach()
which can be used for similar tasks. They often have optimized implementations within the engine and might offer better performance than explicit loops in certain scenarios. s.split('').map(c => n.includes(c) ? String.fromCharCode(c.charCodeAt() + 65248) : c).join('');
Key Takeaways:
for
loop and a for...of
loop often comes down to readability and personal preference.