I'm trying to serialize a reasonably large amount of data with protobuf.net. I'm hitting problems with OutOfMemoryException
s being thrown. I'm trying to stream the data using IEnumerable<DTO>
so as not to use too much memory. Here's a simplified version of the program that should cause the error:
class Program
{
static void Main(string[] args)
{
using (var f = File.Create("Data.protobuf"))
{
ProtoBuf.Serializer.Serialize<IEnumerable<DTO>>(f, GenerateData(1000000));
}
using (var f = File.OpenRead("Data.protobuf"))
{
var dtos = ProtoBuf.Serializer.DeserializeItems<DTO>(f, ProtoBuf.PrefixStyle.Base128, 1);
Console.WriteLine(dtos.Count());
}
Console.Read();
}
static IEnumerable<DTO> GenerateData(int count)
{
for (int i = 0; i < count; i++)
{
// reduce to 1100 to use much less memory
var dto = new DTO { Data = new byte[1101] };
for (int j = 0; j < dto.Data.Length; j++)
{
// fill with data
dto.Data[j] = (byte)(i + j);
}
yield return dto;
}
}
}
[ProtoBuf.ProtoContract]
class DTO
{
[ProtoBuf.ProtoMember(1, DataFormat=ProtoBuf.DataFormat.Group)]
public byte[] Data
{
get;
set;
}
}
Interestingly, if you reduce the size of the array on each DTO
to 1100 the problem goes away! In my actual code, I'd like to do something similar but it's an array of floats that I'll be serializing, not bytes. N.B. I think you can skip the filling with data part to speed up the problem.
This is using protobuf version 2.0.0.594. Any help would be much appreciated!
EDIT:
Same problem seen with version 2.0.0.480. Code wouldn't run with version 1.0.0.280.