2 ms·
If you care about performance, those are both insane ways to count newlines. Try a loop of indexOf() and watch it absolutely spank the splitting method. That wa
by electroly 3y ago
If you care about performance, those are both insane ways to count newlines. Try a loop of indexOf() and watch it absolutely spank the splitting method. That was the first thing that popped into my head, and in testing it appears to be 5x the speed of splitting (and 0x the memory consumption).
- lolinder 3y agoHaha, 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.