4 ms·
Alternatively: "Iterating through the string, take each character and dump it plus a space to a temp string. Return the temp string trimmed." I wouldn't say th
by bulatb 13y ago
Alternatively: "Iterating through the string, take each character and dump it plus a space to a temp string. Return the temp string trimmed."
I wouldn't say that's any worse, especially in this scenario. But they should get it just as quickly.
Edit: trim the string. :)
- jaredsohn 13y agoI would think an advantage to using split/join is that you aren't concatenating a lot of immutable strings together (although if this only happens one time and for a short string, it may not matter.) Edit: Not tested myself. I had a suspicion about it and "confirmed" it via an older post that is perhaps outdated now. Updated this comment to sound less authoritative ("I would think").
- parksy 13y agoSomeone already set up a jsperf test for this an hour or so ago, so I added my regex solution. http://jsperf.com/spacify/2 http://jsperf.com/spacify/2 On my machine, I was surprised to see that the for loop is the fastest (Chrome + Crunchbang). I'd guess that this is probably because looping structures are heavily optimized in modern JS engines.
- bulatb 13y agoOne thing I've learned from jsPerf is that this sort of micro-tuning tends to be particularly fruitless in JavaScript. Even if a tweak increases speed consistently across the target browsers, there's no telling which will optimize what cases in the next few versions. Basic things like caching DOM lookups are always good, but not so much the little things.
- parksy 13y agoYup, I just ran the tests again and the results are completely different and what difference there is is basically negligible.
- bulatb 13y agoThe join() hack used to be significantly faster for many/long strings a couple years ago, but I wouldn't be surprised if things have changed since then. I'd be interested to see your results. Edit: Apparently the loop is faster.[0] :) [0] https://news.ycombinator.com/item?id=7149833 https://news.ycombinator.com/item?id=7149833
- vkjv 13y agoThe loop doesn't even do the same thing since it adds an extra space at the end. Fixed: http://jsperf.com/spacify/4 http://jsperf.com/spacify/4