Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More optimisations #4

Open
ghost opened this issue Jul 17, 2011 · 0 comments
Open

More optimisations #4

ghost opened this issue Jul 17, 2011 · 0 comments

Comments

@ghost
Copy link

ghost commented Jul 17, 2011

I found that (in chrome) using string.replace is faster than string.split.join. Also performance can be boosted by caching regex objects used in string.replace once they are created. Here are some benchmarks. Regards.

var str = '& &amp;<some html="string">html for the win</html>'
var r1 = /&(?!\w+;)/g;

var r2 = /</g;
var r3 = />/g;
var r4 = /"/g;
var r5 = /'/g;

var t = (new Date()).valueOf();
for(var i = 0; i < 100000; ++i) {
    var rr = str.replace(/&(?!\w+;)/g, '&#38;');
}
console.log('String.replace with new regexp every time', (new Date()).valueOf() - t);


var t = (new Date()).valueOf();
for(var i = 0; i < 100000; ++i) {
    var rr = str.replace(r1, '&#38;');
}
console.log('String.replace reusing regexp', (new Date()).valueOf() - t);

var t = (new Date()).valueOf();
for(var i = 0; i < 100000; ++i) {
    var rr = str.split('<').join('&#60;').split('>').join('&#62;')
                            .split('"').join('&#34;').split("'").join('&#39;');
}
console.log('String.split.join', (new Date()).valueOf() - t);


var t = (new Date()).valueOf();
for(var i = 0; i < 100000; ++i) {
    var rr = str.replace(r2, '&#60;').replace(r3, '&#62;').replace(r4, '&#34;').replace(r5, '&#39;');
}
console.log('String.replace (reusing regexps)', (new Date()).valueOf() - t);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

0 participants