[removed] indexOf vs. Match when Searching Strings?

前端 未结 9 1570
感情败类
感情败类 2020-12-04 13:16

Readability aside, are there any discernable differences (performance perhaps) between using

str.indexOf("src") 

and



        
9条回答
  •  借酒劲吻你
    2020-12-04 13:18

    Your comparison may not be entirely fair. indexOf is used with plain strings and is therefore very fast; match takes a regular expression - of course it may be slower in comparison, but if you want to do a regex match, you won't get far with indexOf. On the other hand, regular expression engines can be optimized, and have been improving in performance in the last years.

    In your case, where you're looking for a verbatim string, indexOf should be sufficient. There is still one application for regexes, though: If you need to match entire words and want to avoid matching substrings, then regular expressions give you "word boundary anchors". For example:

    indexOf('bar')
    

    will find bar three times in bar, fubar, barmy, whereas

    match(/\bbar\b/)
    

    will only match bar when it is not part of a longer word.

    As you can see in the comments, some comparisons have been done that show that a regex may be faster than indexOf - if it's performance-critical, you may need to profile your code.

提交回复
热议问题