String#endsWith: slice vs indexOf

JavaScript performance comparison

Test case created by Daniel Hug

Preparation code

var bigLongString = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sit amet sem sit amet nisl ornare egestas. Praesent ullamcorper turpis vitae mi hendrerit, vel sagittis risus tincidunt. Duis nec nisi et lectus porta ornare at eget odio. Nunc iaculis vulputate ante, quis scelerisque lacus bibendum vitae. Proin vehicula urna vel luctus adipiscing. Suspendisse potenti. Praesent risus elit, dapibus vitae enim sed, interdum ultricies augue. Sed ut eros odio. Morbi iaculis venenatis diam ac luctus.";
var subStrSuccess = "Lorem ipsum";
var subStrFail = "Cracker Jack";

// Math / Number polyfills needed in some browsers:
if (!Number.toInteger) Number.toInteger = function(value) {
        var number = +value;
        if (, NaN)) return +0;
        if (number === 0 || !Number.isFinite(number)) return number;
        return Math.sign(number) * Math.floor(Math.abs(number));

if (!Math.sign) Math.sign = function(value) {
        var number = +value;
        if (number === 0) return number;
        if (, NaN)) return number;
        return (number < 0) ? -1 : 1;

// indexOf:
function a(searchStr) {
                'use strict';
                if (this === null) throw new TypeError("Cannot call method 'startsWith' of null");
                if (this === undefined) throw new TypeError("Cannot call method 'startsWith' of undefined");
                searchStr = String(searchStr);
                var thisStr = String(this);
                var start = Math.max(Number.toInteger(arguments[1]), 0);
                if ((searchStr.length + start) > thisStr.length) return false;
                var index = '', searchStr, start);
                return index === start;

// slice:
function b(searchStr) {
                "use strict";
                if (this == null) throw new TypeError("Cannot call method 'endsWith' of null or undefined");
                var thisStr = String(this);
                searchStr = String(searchStr);
                var thisLen = thisStr.length;
                var pos = (arguments[1] === undefined) ?
                        thisLen : Number.toInteger(arguments[1]);
                var end = Math.min(pos, thisLen);
                return thisStr.slice(end - searchStr.length, end) === searchStr;

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
indexOf success, subStrSuccess);
indexOf fail, subStrFail);
slice success, subStrSuccess);
slice fail, subStrFail);

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

Compare results of other browsers


Comment form temporarily disabled.

Add a comment