Question

Learning javascript and came across something like this:

if (obj.indexOf("someValue") > -1) {
    do.something();
}

Without posting the whole script, the indexOf() method was only being used to check for a value in a string.

My question is why you would do that instead of:

if (obj.match(/someValue/g)) {
    do.something();
}

Is this for legacy browser support or is it faster for some reason?

Était-ce utile?

La solution

I think the reason is that RegExp match() is indeed slower than indexOf

You can check here.

From the above site only the code:

<script>
  var str = "hello world!";
</script>

5,616,069 Ops/sec Using match time taken is ±3.05% 55% slower

12,306,269 Ops/sec Using indexOf() time taken is ±2.51% fastest

Autres conseils

match() uses regex, regex is slower than indexOf().

Generally speaking it is really more a question of taste. Some could argue though that indexOf is slightly faster.

Well, indexOf() is a simple string search, while obj.match() is regExp search. It's just two different things.

When I need to check if is it rainig right now, I just look out the window instead of turning on TV and looking for weather forecast.

P.S.: Btw your "/g" makes global search, when indexOf() returns only the first occurrence. So in your case indexOf() becomes faster (compairing to obj.match()) as input string becomes longer.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top