Search code examples
c#stringperformanceconcatenation

Most efficient way of adding/removing a character to beginning of string?


I was doing a small 'scalable' C# MVC project, with quite a bit of read/write to a database.

From this, I would need to add/remove the first letter of the input string.


'Removing' the first character is quite easy (using a Substring method) - using something like:

String test = "HHello world";
test = test.Substring(1,test.Length-1);

'Adding' a character efficiently seems to be messy/awkward:

String test = "ello World";
test = "H" + test;

Seeing as this will be done for a lot of records, would this be be the most efficient way of doing these operations?

I am also testing if a string starts with the letter 'T' by using, and adding 'T' if it doesn't by:

String test = "Hello World";
if(test[0]!='T')
{
    test = "T" + test;
}

and would like to know if this would be suitable for this


Solution

  • Both are equally efficient I think since both require a new string to be initialized, since string is immutable.

    When doing this on the same string multiple times, a StringBuilder might come in handy when adding. That will increase performance over adding.

    You could also opt to move this operation to the database side if possible. That might increase performance too.