问题描述
关于没有提供太多细节。 (简而言之:它返回字符串的规范表示,允许使用 ==
比较实习字符串)
The Javadoc about String.intern()
doesn't give much detail. (In a nutshell: It returns a canonical representation of the string, allowing interned strings to be compared using ==
)
- 我什么时候才能使用这个函数来支持
String.equals()
? - 是否有Javadoc中没有提到的副作用,即JIT编译器或多或少的优化?
- 是否还有
String.intern()$ c $的使用c>?
- When would I use this function in favor to
String.equals()
? - Are there side effects not mentioned in the Javadoc, i.e. more or less optimization by the JIT compiler?
- Are there further uses of
String.intern()
?
推荐答案
当您需要速度时,因为您可以通过引用比较字符串(= =快于等于)
when you need speed since you can compare strings by reference (== is faster than equals)
主要的缺点是你必须记住确保你实际上做了你要比较的所有字符串intern()。很容易忘记intern()所有字符串,然后你可以得到令人困惑的错误结果。此外,为了每个人的利益,请务必非常清楚地记录您依赖内部化的字符串。
The primary disadvantage is that you have to remember to make sure that you actually do intern() all of the strings that you're going to compare. It's easy to forget to intern() all strings and then you can get confusingly incorrect results. Also, for everyone's sake, please be sure to very clearly document that you're relying on the strings being internalized.
如果您决定内化字符串,第二个缺点是intern()方法相对昂贵。它必须管理唯一字符串池,以便它完成相当多的工作(即使字符串已经内化)。所以,在你的代码设计中要小心,这样你就可以在输入中输入所有适当的字符串,这样你就不必再担心它了。
The second disadvantage if you decide to internalize strings is that the intern() method is relatively expensive. It has to manage the pool of unique strings so it does a fair bit of work (even if the string has already been internalized). So, be careful in your code design so that you e.g., intern() all appropriate strings on input so you don't have to worry about it anymore.
(来自JGuru)
第三个缺点(仅限Java 7或更低版本):在PermGen空间中使用的实际字符串通常非常小;你可能会遇到一个有足够空闲堆空间的OutOfMemoryError。
Third disadvantage (Java 7 or less only): interned Strings live in PermGen space, which is usually quite small; you may run into an OutOfMemoryError with plenty of free heap space.
(来自Michael Borgwardt)
(from Michael Borgwardt)
这篇关于使用java.lang.String.intern()是一种好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!