1

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?

2

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.