2
str.indexOf(substr) == 0

str.slice(0, 10) == substr

Which one of the above two is better? Is there any better way?

ithinc
  • 83
  • 5

3 Answers3

6

The performance of the first depends on the length of the string str as it requires scanning the entire string. If str is large it could take a long time to find whether or not the substring is contained within it.

If your input string could be large prefer the second.

Another option is:

str.lastIndexOf(substr, 0) == 0

This avoids scanning the entire string and avoids creating a temporary string.

If performance matters, I'd suggest measuring it for your specific data.

Mark Byers
  • 767,688
  • 176
  • 1,542
  • 1,434
2

A (very) quick test suggests that the difference is probably negligible in Chrome, but that Firefox is substantially quicker with indexOf (for short strings, at least).

lonesomeday
  • 224,675
  • 49
  • 309
  • 312
1

Off the top of my head, I'd say to use:

str.indexOf(substr) == 0;

Simply because it doesn't need to create a new string from the first. Performance testing would be needed. Could vary by browser.

user113716
  • 310,407
  • 61
  • 442
  • 435
  • Performance shouldn't be an issue. Creating a 10 character string will take less than negible time anyway. –  Jan 02 '11 at 15:42
  • @delnan: I agree, but the question was asked, and for me this version edges out the other simply because of the fact that the other creates a new String that just gets discarded after the comparison. – user113716 Jan 02 '11 at 15:45