11 ms·
I find it interesting how slow some standard library functions can be if your code is really pushing them in untypical ways. It's not actually that surprising i
by fabian2k 6y ago
I find it interesting how slow some standard library functions can be if your code is really pushing them in untypical ways. It's not actually that surprising in most cases once you remember that the library functions often have to handle expensive edge cases and invalid input.
I did encounter a similiar issue a while ago in Javascript parsing files that could be hundreds of megabytes with mostly floating point numbers as text in them. parseFloat turned out to be the bottleneck in this case after optimizing everything else, and I used a very naive (and entirely wrong) function to parse the floats that worked very similar like the earlier optimization in this case. Simply reading each digit, multiplying it by 10*position and adding it all up. Of course this creates the wrong result because of rounding, but it was close enough for my use case. And it was actually something like 2-3 times faster for the overall runtime (not just microbenchmarking the float parsing). What helped here was that the number of digits was generall low, so you typically had ~3 digits after the dot, not the maximum floats could represent.
I'm pretty sure someone that knows what they're doing could have written an even faster and more accurate version there given the same constraints, but I was surprised just by how much I could beat the library function for my specific, restricted use case with a very naive implementation.