使用 java.lang.String.intern() 是好习惯吗? [英] Is it good practice to use java.lang.String.intern()?

查看:27
本文介绍了使用 java.lang.String.intern() 是好习惯吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于的JavadocString.intern() 没有提供太多细节.(简而言之:它返回字符串的规范表示,允许使用 == 比较内部字符串)

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() 还有其他用途吗?
  • 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()?

推荐答案

我什么时候用这个函数代替 String.equals()

When would I use this function in favor to String.equals()

当您需要速度时,因为您可以通过引用比较字符串(== 比等于快)

when you need speed since you can compare strings by reference (== is faster than equals)

Javadoc 中有没有提到的副作用?

Are there side effects not mentioned in the Javadoc?

主要的缺点是您必须记住确保您确实对要比较的所有字符串执行了 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() 方法相对昂贵.它必须管理唯一字符串池,因此它会做一些工作(即使字符串已经被内部化).因此,在您的代码设计中要小心,例如,在输入中使用 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.

(来自迈克尔·博格沃特)

(from Michael Borgwardt)

这篇关于使用 java.lang.String.intern() 是好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆