Javascript split/join vs replace

Sep 2 2011 8:18 AM SEP 2 2011 8:18 AM
.split(" ").join("") vs .replace(/ /g, "")Javascript

Recently I heard a extremely random agrument about a simple Javascript method.

Basically take a random string.

Lorem  ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod  tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim  veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea  commodo consequat. Duis aute irure dolor in reprehenderit in voluptate  velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint  occaecat cupidatat non proident, sunt in culpa qui officia deserunt  mollit anim id est laborum.

Multiply this about 500 more times... And then run these two seperate items...

var str = "Lorem  ipsum dolor sit amet, consectetur adipisicing elit, sed do  eiusmod  tempor incididunt ut labore et dolore magna aliqua. Ut enim ad  minim  veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip  ex ea  commodo consequat. Duis aute irure dolor in reprehenderit in  voluptate  velit esse cillum dolore eu fugiat nulla pariatur. Excepteur  sint  occaecat cupidatat non proident, sunt in culpa qui officia  deserunt  mollit anim id est laborum.";
alert( str.split(" ").join("") );
alert( str.replace(/ /g, "") );

Which one is faster?

Well because that can be difficult I happen to come across a speed tester... It proves that .replace is actually significantly faster and depending on the browser can be as much as 1% faster than split/join. Not only that but if you think about what split actually does this could be potentially a MASSIVE memory hog. In general this also is dependant on the browser. Each tends to handle arrays / strings differently. Because of this one may favor one method over the other.

Go to this link and check it out in a couple different browsers. jsperf.com

***EDIT:

Based on relooking at the test split(" ").join("") is faster. However the difference only begins to appear in larger examples. In the larger examples of the jsperf.com where 10,000 items in an array are done it has roughly has a 13% difference. Even still the difference in actual time is really small.

.052 for split/join

.068 for replace.

I don't know but .016 difference is not a huge difference. Anything in miliseconds a person wont be able to even see. If we were looking at something in the "seconds" range I would say then you might want to look at split/join. Otherwise its really preference. I know for myself I would still want to see the memory usage here as again split converts a string to an array and then re-concats it into a string. Which if you already have a memory intensive application this may not be a valid option.

*****

In the end my thoughts are that this is choice. With it being so close depending on the release of the browser you are using it could switch.

A great place to check speeds and accuracy is: jsperf.com