Reputation: 6447
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
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
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
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:
unsafe
Upvotes: 13
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