How can C#'s string.IndexOf perform so fast, 10 times faster than ordinary for loop find?

后端 未结 5 1523
野趣味
野趣味 2021-02-19 03:41

I have a very long string (60MB in size) in which I need to find how many pairs of \'<\' and \'>\' are in there.


I have first tried my own way:

5条回答
  •  无人及你
    2021-02-19 04:14

    I would expect string.IndexOf compared to your first code sample to run at least twice as fast (besides any other optimizations that might be done there) since you check for both start and end character in each of your iterations. Your implementation with string.IndexOf on the other hand will check for the end character only after it has successfully found a start character. This cuts the number of operations on each iteration down significantly (one less comparison).

提交回复
热议问题