Palindrome

JavaScript performance comparison

Test case created by ggorlen

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  let a = [];
  let b = [];
  
  const randChar = _ => Math.random() > 0.2 ?
    String.fromCharCode(~~(Math.random() * 26 + 65)) : " "
  ;
  
  for (let i = 0; i < 10000; i++) {
    a.push(randChar());
    b.push(randChar());
  }
  
  
  a = a.join``;
  b = b.join`` + b.reverse().join``;

};
</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
Using functions
const palindrome = str => {
  str = str.replace(/[^a-z\d]/gi, "").toLowerCase();
  return str === str.split("").reverse().join("");
};

palindrome(a);
palindrome(b);
pending…
Using two pointers
const palindrome = str => {
  str = str.replace(/[^a-z\d]/gi, "").toLowerCase();
  let left = 0;
  let right = str.length;

  while (left < right) {
    if (str[left++] !== str[--right]) {
      return false;
    }
  }

  return true;
};

palindrome(a);
palindrome(b);
pending…

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

Compare results of other browsers

0 Comments