Peter Petrov’s Weblog

var me = from practice in programming where practice.IsBestPractice && practice.UseLambda select practice.OptimalPerformance;

Parse string having comma separated integers August 1, 2011

Filed under: .NET Framework,C# — ppetrov @ 8:01 pm
Tags: ,

I’ve read a blog post about splitting a string containing comma separated integers and then creating an array. It’s a very short and simple code but there’s a little problem – it uses the Split() method and the result is an array, potentially big array. What if you only need the first 10 results out of ten thousand integers ? You will do the work to split ten thousand integers and you will consume a lot memory then you need and finally you will create a lot of garbage. I’ve written a class to solve this issues.

public class IntConverter
{
private readonly char _separator;

public IntConverter()
: this(',')
{
}

public IntConverter(char separator)
{
_separator = separator;
}

public IEnumerable<int> From(string input)
{
if (input == null) throw new ArgumentNullException("input");

return FromImplementation(input.Trim(), _separator);
}

public string To(IEnumerable<int> numbers)
{
if (numbers == null) throw new ArgumentNullException("numbers");

var buffer = new StringBuilder();

foreach (var n in numbers)
{
if (buffer.Length > 0)
{
buffer.Append(_separator);
}
buffer.Append(n.ToString());
}

return buffer.ToString();
}

private IEnumerable<int> FromImplementation(string input, char separator)
{
if (input == string.Empty)
{
yield break;
}

var buffer = new StringBuilder();

var symbols = input.ToCharArray();
for (var i = 0; i < symbols.Length; i++)
{
var symbol = symbols[i];
var isSeparator = (symbol == separator);
if (isSeparator)
{
yield return int.Parse(buffer.ToString());
buffer.Length = 0;
}
else
{
buffer.Append(symbol);
}
}

yield return int.Parse(buffer.ToString());
}
}

I wish there will be an overload of int.Parse or int.TryParse witch accepts StringBuilder as input to reduce even more the memory usage in this scenario.

 

 
Follow

Get every new post delivered to your Inbox.