I wrote a small program using a custom indexOf function but wanted to dismiss it in favour of the system string.IndexOf() method.
But before I started refactoring I wrote a small test program out of curiosity to see just see how bad my function was behaving in comparison of system string.IndexOf()
what I observed was the fact that system string.IndexOf seems to be a magnitude slower than iterating a array.
Processing random random string at 1000000 characters.
Processing method 1 system string.IndexOf
index 999999 took 620036 ticks
Processing method 2 custom IndexOf
index 999999 took 130007 ticks
So my question is really; Am I doing it wrong? Shouldn’t a system function much faster than anything else I write in c#?
tl;dr
the test scenario
first I set up some test data, filling a random string with some data
StringBuilder sb = new StringBuilder();
Random r = new Random();
string c = "abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVXYZ0123456789";
long before;
long after;
for (int i = 0; i < 1000000; i ++) sb.Append(c[r.Next(c.Length)]);
and then insert something at the end of the array that I want to search for, worst case scenario
int j = sb.Length - 1 ;
sb[j] = '"';
method 1: system string.IndexOf
and then check how many ticks is used by system string.IndexOf()
before = DateTime.Now.Ticks;
index = text.IndexOf("\"");
after = DateTime.Now.Ticks;
method 2:custom method
and after that I run my custom code which is just a static function with a while loop iterating over a character array.
before = DateTime.Now.Ticks;
index = IndexOf(text, 0, '"', '/');
after = DateTime.Now.Ticks;
I think the difference here is that when you’re calling
String.IndexOfyou’re using a string literal, and your custom function is using a character literal.Without having seen your custom implementation, I’d guess the
String.IndexOfmethod is more correct (locales, unicode, and all that stuff).