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.
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);
Welcome Willi! 😉