regex-and-loop

JavaScript performance comparison

Test case created by pranavcbalan

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  function checkZfn(s) {
    var n = s.length;
    var z = Array(n).fill(0);
    var i, l, r;
    for (i = 1, l = 0, r = 0; i < n; ++i) {
      if (i <= r)
        z[i] = Math.min(r - i + 1, z[i - l]);
      while (i + z[i] < n && s[z[i]] == s[i + z[i]])
        ++z[i];
      if (i + z[i] - 1 > r)
        l = i, r = i + z[i] - 1;
    }
    return z.some(( v,i) => (i + v) === n && n % i === 0)
  }
  
  function checkRec(str)
  {
    if( str.length==1 ) return true; // trivial case
    for( var i=1;i<str.length/2;i++ ) { // biggest possible repeated pattern has length/2 characters
  
      var p = str.substring(0, i);
      if( isRepeating(p,str) ) return true;
    }
    return false;
  }
  
  
  function isRepeating(p, str)
  {
    if( str.length>p.length ) { // maybe more than 2 occurences
  
      var left = str.substring(0,p.length);
      var right = str.substring(p.length, str.length);
      return isRepeating(p,left) && isRepeating(p,right);
    }
    else if( str===p ) {
      return true;
    }
    return false;
  }
  
  function checkLoop(str){
    if(!(str.length && str.length - 1)) return false;
    let temp = '';
    for(let i = 0;i<=str.length/2;i++){
      temp += str[i] 
      //console.log(str.replace(new RegExp(temp,"g"),''))
      if(!str.replace(new RegExp(temp,"g"),'')) return true;
    }
    return false;
  }
  
  function checkZmod(s) {
    var n = s.length;
    var z = Array(n).fill(0);
    var i, l, r;
    for (i = 1, l = 0, r = 0; i < n; ++i) {
      if (i <= r)
        z[i] = Math.min(r - i + 1, z[i - l]);
      while (i + z[i] < n && s[z[i]] == s[i + z[i]])
        ++z[i];
  
      if (z[i] + i === n && n % i === 0)
        return true;
      if (i + z[i] - 1 > r)
        l = i, r = i + z[i] - 1;
    }
    return false;
  }
  
  function checkReg(str) {
    return /^(.+)\1+$/.test(str)
  }

};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
z-function
checkZfn('aa');
checkZfn('aaa');
checkZfn('abcabcabc');
checkZfn('aba');
checkZfn('ababa');
pending…
Recursive
checkRec('aa');
checkRec('aaa');
checkRec('abcabcabc');
checkRec('aba');
checkRec('ababa');
pending…
Loop
checkLoop('aa');
checkLoop('aaa');
checkLoop('abcabcabc');
checkLoop('aba');
checkLoop('ababa');
pending…
z modified
checkZmod('aa');
checkZmod('aaa');
checkZmod('abcabcabc');
checkZmod('aba');
checkZmod('ababa');
pending…
Regex
checkReg('aa');
checkReg('aaa');
checkReg('abcabcabc');
checkReg('aba');
checkReg('ababa');
pending…

Compare results of other browsers

Revisions

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

0 Comments