replace.replace vs replace+function

Benchmark created by Jim Montgomery on


Description

compare ways to quickly pad numbers (octets in an ip, for sorting)

Setup

var ip = '1.0.22.123';

Teardown


    var results =(
    ip.replace(/\b[0-9]\b/g,'00$&').replace(/\b\d\d\b/g,'0$&') +' '+ (ip.replace(/\b[0-9]{1,2}\b/g, function(m){ 
        return (m.length === 2 ? '0':'00') + m;
    }))
    );
    if(results !== '001.000.022.123 001.000.022.123') console.warn('replace.replace + replace.function',results);
    
  

Test runner

Ready to run.

Testing in
TestOps/sec
replace.replace
ip.replace(/\b[0-9]\b/g,'00$&').replace(/\b\d\d\b/g,'0$&')
ready
replace.function
ip.replace(/\b[0-9]{1,2}\b/g, function(m){ 
    return (m.length === 2 ? '0':'00') + m;
})
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Jim Montgomery on