Thursday, September 23, 2010

string.replace with function benchmarks


function escapeRegExp(s) {
return s.replace(/([-.*+?^${}()|[\]\/\\])/g, '\\$1');
};
function escapeRegExp_asFunction(s) {
return s.replace(/([-.*+?^${}()|[\]\/\\])/g, function(ch) {
return "\\" + ch;
});
};

Test case:

var loops = 10000,
s1 = "abcdefgjklmnoprstuvxyz",
s2 = "-.*+?^${}()|[]/\\",
s3 = "a-a.a*a+a?a^a$a{a}a(a)a|a[a]a/a\\a",
testStrings = [s1, s2, s3];

MSIE 7.0 results

escapeRegExp
78:abcdefgjklmnoprstuvxyz
110:\-\.\*\+\?\^\$\{\}\(\)\|\[\]\/\\
125:a\-a\.a\*a\+a\?a\^a\$a\{a\}a\(a\)a\|a\[a\]a\/a\\a

escapeRegExp_asFunction
110:abcdefgjklmnoprstuvxyz
797:\-\.\*\+\?\^\$\{\}\(\)\|\[\]\/\\
797:a\-a\.a\*a\+a\?a\^a\$a\{a\}a\(a\)a\|a\[a\]a\/a\\a


Using function as second parameter in replace is at least:

796/125 ~= 6 times slower than the first one on MSIE a
173/48 ~= 3 times slower on FF
77/61 ~= same speed on Safari !!!

on test string with half matched chars.

No comments:

Post a Comment