Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

regex - Javascript Performance: How come looping through an array and checking every value is faster than indexOf, search and match?

This came as a huge surprise for me, and I'd like to understand this result. I made a test in jsperf that is basically supposed to take a string (that is part of a URL that I'd like to check) and checks for the presence of 4 items (that are in fact, present in the string).

It checks in 5 ways:

  1. plain indexOf;
  2. Split the string, then indexOf;
  3. regex search;
  4. regex match;
  5. Split the string, loop through the array of items, and then check if any of them matches the things it's supposed to match

To my huge surprise, number 5 is the fastest in Chrome 21. This is what I can't explain.

In Firefox 14, the plain indexOf is the fastest, that one I can believe.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm also surprised but Chrome uses v8, a highly optimized JavaScript engine which pulls all kinds of tricks. And the guys at Google probably have the largest set of JavaScript to run to test the performance of their implementation. So my guess is this happens:

  1. The compiler notices that the array is a string array (type can be determine at compile time, no runtime checks necessary).
  2. In the loop, since you use ===, builtin CPU op codes to compare strings (repe cmpsb) can be used. So no functions are being called (unlike in any other test case)
  3. After the first loop, everything important (the array, the strings to compare against) is in CPU caches. Locality rulez them all.

All the other approaches need to invoke functions and locality might be an issue for the regexp versions because they build a parse tree.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...