mj_
mj_

Reputation: 6447

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.

Upvotes: 4

Views: 2873

Answers (4)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

One obvious drawback to converting a string to char[] is the need to copy: since strings in C# are immutable while arrays are mutable, your code would end up duplicating your gigantic string in its entirety! This will almost certainly dwarf the potential speed gains, if any, to be had after the conversion.

Upvotes: 1

Jon
Jon

Reputation: 437346

First of all: you should measure. Noone can answer this question definitively without measuring.

In this particular case everything indicates that accessing the string directly is better: strings are implemented as arrays of characters in pretty much every language, and converting the string to a char[] manually would require an immediate allocation of another gigantic amount of memory. That can't be good.

But I wouldn't event take my own word for it. Measure.

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062715

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

Upvotes: 13

Tejs
Tejs

Reputation: 41236

string is a char[] array under the hood. So there is literally no difference.

The bigger problem here is that trying to optimize this far down in the stack is probably wasted time, there are probably better improvements to be made elsewhere.

Upvotes: -3

Related Questions