Fastest way to remove first char in a String

Amr Badawy picture Amr Badawy · Jul 11, 2010 · Viewed 298.7k times · Source

Say we have the following string

string data= "/temp string";

If we want to remove the first character / we can do by a lot of ways such as :

data.Remove(0,1);
data.TrimStart('/');
data.Substring(1);

But, really I don't know which one has the best algorithm and doing that faster..
Is there a one that is the best or all are the same ?

Answer

Jon Skeet picture Jon Skeet · Jul 11, 2010

The second option really isn't the same as the others - if the string is "///foo" it will become "foo" instead of "//foo".

The first option needs a bit more work to understand than the third - I would view the Substring option as the most common and readable.

(Obviously each of them as an individual statement won't do anything useful - you'll need to assign the result to a variable, possibly data itself.)

I wouldn't take performance into consideration here unless it was actually becoming a problem for you - in which case the only way you'd know would be to have test cases, and then it's easy to just run those test cases for each option and compare the results. I'd expect Substring to probably be the fastest here, simply because Substring always ends up creating a string from a single chunk of the original input, whereas Remove has to at least potentially glue together a start chunk and an end chunk.