how do I enable string interning in protobuf-net?

偶尔善良 提交于 2019-12-19 08:40:34

问题


I am using v2 rev 421. When I saved the stream produced by protobuf-net and put it through the strings utility, it discovered many duplicate strings. I am talking about the strings produced by the application, which can be interned, but the string interning does not seem to be on by default.

How do I enabled it?

Thanks.


回答1:


There are two separate types of interning here; there's interning while deserializing - this is always enabled, so if duplicates are in the data, you should only see a single .NET string instance in your managed classes, re-used as many times as needed.

There is also interning while serializing, to avoid duplicating data into the stream while serializing. This is not on by default, for the simple reason that no such behaviour is defined in the protobuf spec; protobuf-net tries to stay inside the spec by default, only using extensions on an opt-in basis.

If you want to enable this for protobuf-net=to=protobuf-net usage, then enable the AsReference option for any given string:

[ProtoMember(13, AsReference = true)]
public string Foo { get; set; }

This uses a protobuf-net implementation-specific representation. It won't play very nicely for interop purposes, however. If you need this in an interoperable way, the only thing to do is store the lists separately (perhaps in a List<string> somewhere), and use the position in the list in your data, i.e.

// this is .... uglier, but probably easier if you need cross-platform
public int FooOffset {
    get { return Foos.IndexOf(Foo); }
    set { Foo = Foos[value]; }
}


来源:https://stackoverflow.com/questions/6463460/how-do-i-enable-string-interning-in-protobuf-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!