algorithm - Time Complexity of javascript indexOf method -


i studying big o notation technical interview , realized javascript's indexof method may have time complexity of o(n) traverses through each element of array , returns index found.

we know time complexity of o(n^2) (n square) not performance measure larger data.

so bad idea use indexof inside loops? in javascript, common see code indexof method being used inside loops, may measure equality or prepare object.

rather arrays, should prefer objects wherever necessary provide lookup constant time performance o(1).

any suggestions appreciated.

to honest, tl;dr. but, did speed tests of various ways of checking occurrences in string (if goal using indexof. if trying position of match, don't know how there). ways tested were:

  • .includes()
  • .match()
  • .indexof()

(there variants such .search(), .lastindexof(), etc. have not tested).

here test:

var test = 'test string';    console.time('match');  console.log(test.match(/string/));  console.timeend('match');    console.time('includes');  console.log(test.includes('string'));  console.timeend('includes');    console.time('indexof');  console.log(test.indexof('string') !== 0);  console.timeend('indexof');

i know not loops, show same speed. , honestly, each different things, depending on need (do want search regex? need pre ecmascript 2015 compatible? etc. - have not listed of them) necessary analyze much?

from tests, indexof() win, 1 of other ones win.


Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -