JQuery grep(…) VS native JavaScript filter(…) function performance

后端 未结 1 570
难免孤独
难免孤独 2020-12-10 03:51

I measured the execution times of those two functions:

  • jQuery grep function
  • Native JavaScript filter function

The execution of followin

相关标签:
1条回答
  • 2020-12-10 03:58

    By comparing the actual jQuery function $.grep uses on the page

    function (a, b, c) {
        var d = [],
            e;
        c = !! c;
        for (var f = 0, g = a.length; f < g; f++) e = !! b(a[f], f), c !== e && d.push(a[f]);
        return d
    }
    

    (check here for non-minified, thanks Alexander) against the algorithm specified for

    Array.prototype.filter.

    It looks to me like .filter forces its this to Object, checks the callback IsCallable and sets this in it as well as checking for existence of property in each iteration, whereas .grep assumes and skips these steps, meaning there is slightly less going on.

    Combine this with how good the JavaScript compiler in Chrome is and you might find the speed difference.

    Adding some of these into $.grep would make it look like

    function (elems, callback, inv, thisArg) {
        var ret = [],
            retVal;
        inv = !!inv;
        for (var i = 0, length = elems.length; i < length; i++) {
            if (i in elems) { // check existance
                retVal = !!callback.call(thisArg, elems[i], i); // set callback this
                if (inv !== retVal) {
                    ret.push(elems[i]);
                }
            }
        }
        return ret;
    }
    

    and take about the same time as .filter (modified Alexander's jsperf).

    0 讨论(0)
提交回复
热议问题