views:

454

answers:

3

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?

+2  A: 

Here's a nice blog post to start with. But you really should measure to know which is faster.

dirkgently
After reading that page it seems that replace is the way to go. Additionally it supports regex too.
Amarghosh
Thanks for that - I've just been refactoring all my old string.split().join().split().join()... methods to use regexp and wondered if it was worth all the effort.
Reuben
+2  A: 

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.

Tom
+4  A: 

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
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
Thanks for running the test - it seems like replace() is the way to go for clarity's sake.
Reuben