本文介绍了真实生活,在Java中使用String.intern()的实际例子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看过很多原始的例子,描述了String intern()的工作原理,但是我还没有看到一个可以从中受益的真实用例。



我能想到的唯一情况是拥有一个接收大量请求的Web服务,由于僵化的架构,每个请求都非常相似。通过intern()在这种情况下使用请求字段名称,可以显着减少内存消耗。



任何人都可以提供在生产环境中使用intern()的示例取得了巨大成功?也许是一个流行的开源产品中的一个例子?



编辑:我指的是手工实习,而不是保证实际的字符串文字等。

解决方案

如果您的 N 字符串只能<$>,则实习非常有用c $ c> K 不同的值,其中 N 远远超过 K 。现在,不是在内存中存储 N 字符串,而是只存储 K



例如,您可能有一个 ID 类型,其中包含5位数字。因此,只有 10 ^ 5 不同的值。假设您现在正在解析一个包含许多对 ID 值的引用/交叉引用的大型文档。假设这个文件有 10 ^ 9 引用总数(显然在文档的其他部分重复了一些引用)。



所以 N = 10 ^ 9 K = 10 ^ 5 在这种情况下。如果你没有实习字符串,你将在内存中存储 10 ^ 9 字符串,其中许多字符串等于(通过)。如果您 intern()您解析文档时获得的 ID 字符串,并且您没有保留任何对从文档中读取的未处理字符串的引用(因此它们可以被垃圾收集),那么你将永远不需要在内存中存储超过 10 ^ 5 的字符串。 / p>

I've seen many primitive examples describing how String intern()'ing works, but I have yet to see a real-life use-case that would benefit from it.

The only situation that I can dream up is having a web service that receives a considerable amount of requests, each being very similar in nature due to a rigid schema. By intern()'ing the request field names in this case, memory consumption can be significantly reduced.

Can anyone provide an example of using intern() in a production environment with great success? Maybe an example of it in a popular open source offering?

Edit: I am referring to manual interning, not the guaranteed interning of String literals, etc.

解决方案

Interning can be very beneficial if you have N strings that can take only K different values, where N far exceeds K. Now, instead of storing N strings in memory, you will only be storing up to K.

For example, you may have an ID type which consists of 5 digits. Thus, there can only be 10^5 different values. Suppose you're now parsing a large document that has many references/cross references to ID values. Let's say this document have 10^9 references total (obviously some references are repeated in other parts of the documents).

So N = 10^9 and K = 10^5 in this case. If you are not interning the strings, you will be storing 10^9 strings in memory, where lots of those strings are equals (by Pigeonhole Principle). If you intern() the ID string you get when you're parsing the document, and you don't keep any reference to the uninterned strings you read from the document (so they can be garbage collected), then you will never need to store more than 10^5 strings in memory.

这篇关于真实生活,在Java中使用String.intern()的实际例子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 02:17