lastIndexOf versus split

JavaScript performance comparison

Revision 2 of this test case created by Gabriel R. Giannattasio

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  function ext(path) {
      var final = path.substr(path.lastIndexOf('/') + 1);
      var separador = final.lastIndexOf('.');
      return separador <= 0 ? '' : final.substr(separador + 1);
  }
  
  function ext2(path) {
      var ext = path.split('/').pop();
      return ext.indexOf('.') < 1 ? '' : ext.split('.').pop();
  }
  
  function ext3(path) {
      var idx = (~-path.lastIndexOf(".") >>> 0) + 2;
      return path.substr((path.lastIndexOf("/") + 1 > idx ? -1 >>> 0 : idx));
  }
  
  function ext4(path) {
    idx = (~-path.lastIndexOf(".") >>> 0) + 2;
    path.substr((-path.lastIndexOf("/") + idx >>> idx) + idx);
  }

};
</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
lastIndexOf
ext('bar.ext');
ext('foo/bar.ext');
ext('foo.bar/sem_ext');
ext('.sem_ext');
pending…
split
ext2('bar.ext');
ext2('foo/bar.ext');
ext2('foo.bar/sem_ext');
ext2('.sem_ext');
pending…
math lastIndexOf
ext3('bar.ext');
ext3('foo/bar.ext');
ext3('foo.bar/sem_ext');
ext3('.sem_ext');
pending…
math lastIndexOf without conditional
ext4('bar.ext');
ext4('foo/bar.ext');
ext4('foo.bar/sem_ext');
ext4('.sem_ext');
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