regex vs. split

JavaScript performance comparison

Revision 2 of this test case created by Kael

Info

Kael: 2 reasons make dirname2 slow: 1. match group(s) 2. string replacement 3. string extraction

so, i try to make it nearly 3 times faster.

Preparation code

<script>
  function dirname(path) {
   var s = path.split('/').slice(0, -1).join('/');
   return s ? s : '.';
  }
 
  function dirname2(path) {
   var s = ('./' + path).replace(/(.*)?\/.*/, '$1').substring(2);
   return s ? s : '.';
  }
 
  function dirname3(path) {
   var s = (path).match(/.*(?=\/.*$)/);
   return (s ? s[0] : '.') + '/';
  }
</script>

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
split
dirname('a/b/c.js');
dirname('a/b/c');
dirname('a/b/c/');
dirname('d.js');
pending…
regex
dirname2('a/b/c.js');
dirname2('a/b/c');
dirname2('a/b/c/');
dirname2('d.js');
pending…
regex match
dirname3('a/b/c.js');
dirname3('a/b/c');
dirname3('a/b/c/');
dirname3('d.js');
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. Here’s a list of current revisions for this page:

1 comment

Qifeng Liu commented :

最后一种方法太秒了,膜拜

Add a comment