简体   繁体   English

如何在protobuf-net中启用字符串实习?

[英]how do I enable string interning in protobuf-net?

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. 我正在使用v2 rev 421.当我保存protobuf-net生成的流并通过字符串实用程序时,它发现了许多重复的字符串。 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. 谢谢。

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. 在反序列化时有实习 - 这始终是启用的,因此如果数据中有重复项,您应该只在托管类中看到一个.NET string实例,并根据需要重复使用多次。

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规范中没有定义这样的行为; protobuf-net tries to stay inside the spec by default, only using extensions on an opt-in basis. protobuf-net默认尝试保留在规范内,仅在选择加入的基础上使用扩展。

If you want to enable this for protobuf-net=to=protobuf-net usage, then enable the AsReference option for any given string: 如果要为protobuf-net = to = protobuf-net使用启用此AsReference为任何给定字符串启用AsReference选项:

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

This uses a protobuf-net implementation-specific representation. 这使用了protobuf-net 特定于实现的表示。 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, ie 如果您需要以可互操作的方式使用它,唯一要做的就是单独存储列表(可能在List<string>某处),并使用数据列表中的位置,即

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM