比较数组慢

时间:2012-06-19 08:30:17

标签: javascript knockout.js

我使用比较两个数组的标准方法,但它只是做一个标准的O(n ^ 2) 你们能看到问题吗?

    diffArray: function (arr1, arr2, observableArray, mapping) {
        //We cant sort orginal arrays
        var o = arr1.slice(0);
        var n = arr2.slice(0);

        // sort both arrays (or this won't work)
        var sorter = function (left, right) {
            return mapping.key(left) - mapping.key(right);
        };
        o.sort(sorter); n.sort(sorter);

        // declare temporary variables
        var op = 0; var np = 0;
        var added = []; var removed = [];

        // compare arrays and add to add or remove lists
        while (op < o.length && np < n.length) {
            if (mapping.key(o[op]) < mapping.key(n[np])) {
                // push to diff?
                removed.push(o[op]);
                op++;
            }
            else if (mapping.key(o[op]) > mapping.key(n[np])) {
                // push to diff?
                added.push(n[np]);
                np++;
            }
            else {
                this.diffMembers(o[op], n[np]);
                op++; np++;
            }
        }

        // add remaining items
        if (np < n.length)
            added = added.concat(n.slice(np, n.length));
        if (op < o.length)
            removed = removed.concat(o.slice(op, o.length));

        ko.utils.arrayForEach(removed, function (item) {
            this.itemDeleted(item, mapping);
        }.bind(this));


        ko.utils.arrayForEach(added, function (item) {
            if (observableArray.concurrencyExtendOptions) {
                this.itemAdded(observableArray, item, mapping);
            }
        } .bind(this));
    }

注意: 映射对象只是用户提供的用于比较数组中对象的辅助对象,arr1和arr2是标准JS数组,而observableArray是解包的Knockout数组

它基于C#代码示例,所以JS中的排序算法可能不是很好吗?

1 个答案:

答案 0 :(得分:1)

不确定它会回答你,真的,但这是我用于数组的diff

Array.prototype.diff = function( arr ) {
    return arr.map( function( v ) {
        if ( !~this.indexOf( v ) ) return v;
    }, this ).filter( Boolean );
};

用法:

arr.diff( otherArr );

PS:作为评论发布的时间太长......不确定是否值得回答。
PS2:该函数的原作者:@Esailija