Friday 15 March 2013

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



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

does indexof walk through array or faster? know implementation dependent chrome or firefox do?

the efficient way find first index matching value in unsorted array walk through list in order, o(n). mdn has hints:

returns the first index @ given element can found in array, or -1 if not present.

[...]

fromindex

default: 0 (entire array searched) index start search at. if index greater or equal array's length, -1 returned, means array not searched. if provided index value negative number, taken offset end of array. note: if provided index negative, the array still searched front end back. if calculated index less 0, the whole array searched.

in case you're wondering, here's how webkit implements it:

class="lang-cpp prettyprint-override">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()) homecoming jsvalue::encode(jsundefined()); unsigned index = argumentclampedindexfromstartorend(exec, 1, length); jsvalue searchelement = exec->argument(0); (; index < length; ++index) { jsvalue e = getproperty(exec, thisobj, index); if (exec->hadexception()) homecoming jsvalue::encode(jsundefined()); if (!e) continue; if (jsvalue::strictequal(exec, searchelement, e)) homecoming jsvalue::encode(jsnumber(index)); } homecoming jsvalue::encode(jsnumber(-1)); }

javascript

No comments:

Post a Comment