What is the time complexity of javascript's array.indexOf?

前端 未结 3 1807
一生所求
一生所求 2020-12-09 01:51

Does indexOf simply walk through the array or does it do something that is faster? I know that this is implementation dependent but what does Chrome or Firefox do?

相关标签:
3条回答
  • 2020-12-09 02:01

    In ECMA6, you have the Set(), and then you can do:

    var obj = new Set();
    obj.add(1);
    obj.has(1) === true;
    obj.has(2) === false;
    

    The performance of has is O(1).

    0 讨论(0)
  • 2020-12-09 02:16

    The most efficient way to find the first index matching a value in an unsorted array is to just walk through the list in order, which is O(n). MDN also has some hints:

    Returns the first index at which a given element can be found in the array, or -1 if it is not present.

    [...]

    fromIndex

    Default: 0 (Entire array is searched)
    The index to start the search at. If the index is greater than or equal to the array's length, -1 is returned, which means the array will not be searched. If the provided index value is a negative number, it is taken as the offset from the end of the array. Note: if the provided index is negative, the array is still searched from front to back. If the calculated index is less than 0, then the whole array will be searched.

    In case you're wondering, here's how WebKit implements it:

    EncodedJSValue JSC_HOST_CALL arrayProtoFuncIndexOf(ExecState* exec)
    {
        // 15.4.4.14
        JSObject* thisObj = exec->hostThisValue().toThis(exec, StrictMode).toObject(exec);
        unsigned length = thisObj->get(exec, exec->propertyNames().length).toUInt32(exec);
        if (exec->hadException())
            return JSValue::encode(jsUndefined());
    
        unsigned index = argumentClampedIndexFromStartOrEnd(exec, 1, length);
        JSValue searchElement = exec->argument(0);
        for (; index < length; ++index) {
            JSValue e = getProperty(exec, thisObj, index);
            if (exec->hadException())
                return JSValue::encode(jsUndefined());
            if (!e)
                continue;
            if (JSValue::strictEqual(exec, searchElement, e))
                return JSValue::encode(jsNumber(index));
        }
    
        return JSValue::encode(jsNumber(-1));
    }
    
    0 讨论(0)
  • 2020-12-09 02:21

    With no guarantees about the nature or order of items in an array, you cannot do better than O(n), so it would walk through the array. Even if it was to parallelise the actual search across CPUs (no idea if firefox or chrome do this, but they could), it does not change the time complexity with a finite number of CPUs.

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