Is it any faster to use
myString.replace(/foo/g,"bar")
rather than
myString.split("foo").join("bar")
for long strings in ActionScript 3? Or are they just two comparable methods of achieving the same result?
Is it any faster to use
myString.replace(/foo/g,"bar")
rather than
myString.split("foo").join("bar")
for long strings in ActionScript 3? Or are they just two comparable methods of achieving the same result?
Here's a nice blog post to start with. But you really should measure to know which is faster.
David R. quoted from the blog Dirkgently linked:
The string.split().join() construct is a leftover from AS2 days, where there was no string.replace(). In AS3, it makes no sense to use .split.join, only people who haven’t learned the new replace function would be likely to use it.
Also, the time difference appears to be minimal according to that blog. So yes, replace should be a much cleaner way of doing this.
I used gSkinners PerformaceTest to run a quick test on this. I think the difference is minimal at best. I would say that replace()
would be the preferred option purely because that is what you want to achieve. Using split().join()
is not as clear in its intent.
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
Using replace() (10000 iterations)
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
method...................................................ttl ms...avg ms
[function] 57 0.01
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
Using split().join() (10000 iterations)
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
method...................................................ttl ms...avg ms
[function] 61 0.01
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––