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

后端 未结 5 1530
野趣味
野趣味 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:21

    Using a switch statement instead of an if test speeds things up a little also. This code occasionally beats the indexof code on my machine.

            int count = 0;
            bool open = false;
            for (int j = 0; j < testStr.Length; j++)
            {  
                switch (testStr[j])
                {
                    case '<':
                        open = true;
                        break;
                    case '>':
                        if (open)
                           count++;
    
                        open = false;
                        break;         
                }
            }
    

提交回复
热议问题