2 ms·
Haha, clearly this was a bad example, because you're right, both are bad. I'm recently coming back to JavaScript after years of Kotlin, and I've clearly gotten
by lolinder 3y ago
Haha, clearly this was a bad example, because you're right, both are bad. I'm recently coming back to JavaScript after years of Kotlin, and I've clearly gotten too comfortable with standard libraries that have decent one-liner functions for this kind of thing.
I'm patching in a loop now (though I feel like a regular for loop is more readable than a loop with indexOf).
- electroly 3y agoindexOf() is faster than the naive character-by-character loop because (presumably) it does all the work outside of JavaScript. You only run JavaScript code for each newline that is found rather than for every character. indexOf() may even use SIMD instructions for speed.
- lolinder 3y agoAh, good point. In my case, after benchmarking inside my actual app on real data, all three perform equally well (including the String.split version). Dropping the Regex made the difference between this being the heavy part of the process to it being a rounding error, and there isn't much additional value to be gained. With that in mind, I'd rather go for legibility over speed. I'm going to go with the for loop, though, because the extra memory usage could come back to bite me later.