Reputation:
I'm writing a script to change all the urls of my content over to a new place.
var regex = /.*cloudfront.net/
var pDistro = "newDistro.cloudfront.net/"
for(var i=0;i<strings.length;i++){
strings[i] = strings[i].replace(regex,pDistro);
}
The strings I'm doing replace
on average about 140 characters each. They're urls that follow the format: https://[thing to replace].cloudfront.net/[something]/[something]/[something]
But this operation is terribly slow, taking about 4.5 seconds to process an average-sized array.
Why is this so slow? How can I make this faster?
If this question would be better suited to the codereview stack exchange, or some other site, let me know and I'll move it there.
The data, as it appeared in the db I was pulling from appeared to be 140 characters. During the pull process, some virtualization happened and appended 400 more characters onto the string, so no wonder the regex takes so long.
The 140-character-string loop takes considerably less time, as others have pointed out.
The moral of the story: "Make sure the data you have is what you expect it to be" and "If your regex is taking too long, use smaller strings and a more specific regex (i.e. no wildcard)"
Upvotes: 7
Views: 5818
Reputation: 708156
For such a simple replacement, a regex is likely not the fastest search and replace. For example, if you replace the search with .indexOf()
and then use .slice()
to do the replacement, you can speed it up 12-50x (depending upon browser).
I wasn't sure of the exact replacement logic you want to simulate, but here's a non-regex method that is a lot faster:
var pos, str, target = "cloudfront.net/";
var pDistro = "https://newDistro.cloudfront.net/"
for(var i = 0; i < urls.length; i++){
str = urls[i];
pos = str.indexOf(target);
if (pos !== -1) {
results[i] = pDistro + str.slice(pos + target.length);
}
}
Adding in the more intelligent regex replacement suggested by others, here's a comparison. The more intelligent regex definitely helps the regex, but it is still slower than just using .indexOf()
and .slice()
and the difference is the most pronounced in Firefox:
See jsperf here: http://jsperf.com/fast-replacer
Upvotes: 6