lukeed / obj-str

A tiny (96B) library for serializing Object values to Strings.
MIT License
249 stars 7 forks source link

Yet another alternative approach to consider #15

Closed onx2 closed 3 months ago

onx2 commented 3 months ago

we can use trimStart and always append the initial blank space, then remove the first space at end of function.

lukeed commented 3 months ago

trimming is a far more expensive operation. if you think about it: it's looping the (potentially entire) string, analyzing character codes to check for "is this whitespace" and then once it finally finds a stopping point, creates a new copy of the string.

compare that against checking if we have a truthy string (cheap), and then mutating the same/existing string at-most-twice per loop.

https://esbench.com/bench/66b69e9b7ff73700a4dec59f

onx2 commented 3 months ago

trimming is a far more expensive operation. if you think about it: it's looping the (potentially entire) string, analyzing character codes to check for "is this whitespace" and then once it finally finds a stopping point, creates a new copy of the string. compare that against checking if we have a truthy string (cheap), and then mutating the same/existing string at-most-twice per loop.

Interesting, timming should be extremely efficient as it doesn't need to loop the entirely of the string and we know this based off the algorithm implemented there will be at most 1 character it checks.

It could also be implemented inversely if I'm thinking about this incorrectly such that the last character is ignored. 🤔

You make a fair point though, thank you for reviewing

lukeed commented 3 months ago

please see the benchmark. the operation itself is as efficient as it can be, but that doesnt mean executing the operation makes the whole transaction efficient.

the point is mostly about the fact that, internally, a loop has to be started wherein string-characters are analyzed, which even if there are 0 leading whitespaces, you're still doing 1x (access + conversion + comparison)... and that's best case scenario. Worst case, you repeat N times only to end up with the equivalent of input.substring(n) which has to build a new string.

making copies of X will never outperform directly mutating X... especially when the conditional for mutating X is a simple length check.

onx2 commented 3 months ago

I'm definitely not trying to argue the benchmark results but I'm just curious now... I thought there was no mutability of String in JS under the hood, and that += operator was effectively creating a new string in memory that is the result of the two?

Also, I expected this behavior to result in worse performance than array manipulation but it seems that there must be some JS engine optimizations that have been baked in? There seems to be a mismatch in the theoretical and real-world 🤔