Deconstructing string paths (pop vs. substr)

JavaScript performance comparison

Test case created

Info

I needed to walk a string path for event bubbling, and wondered what the best way is to "pop off" the last path part of a string.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var path = 'dir1/dir2/dirLongName/even_longer_name_here_almost_unnecessarily_long/things/stuff/file name eventually.jpg';
    var separator = '/';
    var unimportant = 0;
   
    function doSomething(partialPath) {
        // doesn't really matter what we do here, just some basic processing on the string path
        unimportant += partialPath.length;
    }
};
</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
Array.split/pop/join
var apath = path.split(separator);
while (apath.length) {
    doSomething(path);
    apath.pop();
    path = apath.join(separator);
}
pending…
String.lastIndexOf/substr
var i;
while (path.length) {
    doSomething(path);
    i = path.lastIndexOf(separator);
    i = i < 0 ? 0 : i;
    path = path.substr(0, i);
}
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

Add a comment