Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it faster to access char in string via [] operator or faster to access char in char[] via [] operator?

I have a simple question. I'm working with a gigantic string in C# and I'm repeatedly going through it and accessing individual characters via the [] operator. Is it faster to turn the string into a char[] and use the [] operator on the char array or is my approach faster? Or are they both the same? I want my program to be bleeding edge fast.

like image 928
mj_ Avatar asked Sep 06 '25 03:09

mj_


1 Answers

If you need the absolute fastest implementation, then you can drop to unsafe and use pointers:

string s = ...
int len = s.Length;
fixed (char* ptr = s)
{
   // talk to ptr[0] etc; DO NOT go outside of ptr[0] <---> ptr[len-1]
}

that then avoids range checking but:

  • requires unsafe
  • you are to blame if you go outside bounds
like image 170
Marc Gravell Avatar answered Sep 07 '25 19:09

Marc Gravell