String.intern() 的垃圾收集行为

Garbage collection behaviour for String.intern()(String.intern() 的垃圾收集行为)
本文介绍了String.intern() 的垃圾收集行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用 String.intern() 来提高性能,因为我可以使用=="来比较实习字符串,我会遇到垃圾收集问题吗?interned 字符串的垃圾回收机制与普通字符串有何不同?

If I use String.intern() to improve performance as I can use "==" to compare interned string, will I run into garbage collection issues? How does the garbage collection mechanism of interned strings differ from normal strings ?

推荐答案

其实这不是垃圾回收优化,而是字符串池优化.当您调用 String.intern(),你用它的基本引用替换你初始字符串的引用(第一次遇到这个字符串的引用,或者这个引用,如果它还不知道的话).

In fact, this not a garbage collection optimisation, but rather a string pool optimization. When you call String.intern(), you replace reference to your initial String with its base reference (the reference of the first time this string was encountered, or this reference if it is not yet known).

但是,一旦您的字符串在应用程序中不再使用,它​​将成为垃圾收集器问题,因为实习字符串池是 String 类的静态成员,永远不会被垃圾收集.

However, it will become a garbage collector issue once your string is of no more use in application, since the interned string pool is a static member of the String class and will never be garbage collected.

根据经验,我认为最好从不使用这种实习方法,让编译器只将它用于常量字符串,声明如下:

As a rule of thumb, i consider preferrable to never use this intern method and let the compiler use it only for constants Strings, those declared like this :

String myString = "a constant that will be interned";

这更好,因为它不会让您做出错误的假设 == 可以在它不起作用时起作用.

This is better, in the sense it won't let you do the false assumption == could work when it won't.

此外,事实上 String.equals 在底层调用 == 作为优化,确保在后台使用内部字符串优化.这是 == 不应该永远用于字符串的又一证据.

Besides, the fact is String.equals underlyingly calls == as an optimisation, making it sure interned strings optimization are used under the hood. This is one more evidence == should never be used on Strings.

这篇关于String.intern() 的垃圾收集行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How can create a producer using Spring Cloud Kafka Stream 3.1(如何使用Spring Cloud Kafka Stream 3.1创建制片人)
Insert a position in a linked list Java(在链接列表中插入位置Java)
Did I write this constructor properly?(我是否正确地编写了这个构造函数?)
Head value set to null but tail value still gets displayed(Head值设置为空,但仍显示Tail值)
printing nodes from a singly-linked list(打印单链接列表中的节点)
Control namespace prefixes in web services?(控制Web服务中的命名空间前缀?)