Internally there was a race for the best-performing-solution on the following scenario:

A function has a string-parameter containing only digits. The function has to increment the value and return a string having the very same format.
For example: input is ’0100′ the returnvalue is ’0101′

Take this for granted:
- input is always numeric
- the incremented value will never have more chars then the input.

Requirements:
- increment the input-string by one
- padding must be dynamically, depending on the input-value (must also work for ’010′ and ’00100′)

And here is the result, starting with the fastest one:

  • return (int.Parse(input) + 1).ToString().PadLeft(input.Length, ’0′);
  • return (int.Parse(input) + 1).ToString(CultureInfo.InvariantCulture.NumberFormat).PadLeft(input.Length, ’0′);
  • return (Convert.ToInt32(input)+1).ToString(“D” + input.Length);

And the slowest one:

  • return (Convert.ToInt32(input) + 1).ToString(input.Aggregate(“”, (current, t) => current + “0″));

Summary:
- assigning values to variables is slow, so do it all within 1 line.
- using FormatProviders is slow.
- using linq is maximum slow.
- ‘Convert.ToInt32′ checks for NULL, then calls ‘int.Parse’, so better use int.Parse, if you don’t care for null.

Share and Enjoy:
  • Technorati
  • Digg
  • Facebook
  • del.icio.us
  • Live
  • Google Bookmarks
  • DotNetKicks
  • DZone
  • TwitThis
  • Blogosphere News
  • Blogplay
  • LinkedIn
  • MisterWong
  • MisterWong.DE
  • MSN Reporter
  • MyShare
  • RSS
  • StumbleUpon
  • Suggest to Techmeme via Twitter
  • Tumblr
  • Twitter
  • Webnews.de
  • Yahoo! Bookmarks
  • Yigg

2 Responses to “C# Internal Competition”

  1. Willi sagt:

    This should be a little bit faster if readability is not a requirement ;)

    char[] chArray = input.ToCharArray();
    for(int i = chArray.Length – 1; i >= 0; –i) {
    chArray[i] = (char)(((int)chArray[i]-47)%10+48);
    if(chArray[i] != ’0′) break; }
    return new String(chArray);

  2. Daniel Siegl sagt:

    Welcome Willi! ;)

Leave a Reply