什么是 Java 字符串池以及“s"如何与 new String("s") 不同? [英] What is the Java string pool and how is "s" different from new String("s")?

查看:25
本文介绍了什么是 Java 字符串池以及“s"如何与 new String("s") 不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

字符串池是什么意思?以及以下声明之间的区别是什么:

What is meant by String Pool? And what is the difference between the following declarations:

String s = "hello";
String s = new String("hello");

JVM 存储这两个字符串有什么区别吗?

Is there any difference between the storing of these two strings by the JVM?

推荐答案

字符串池是 JVM 对 字符串实习:

The string pool is the JVM's particular implementation of the concept of string interning:

在计算机科学中,字符串实习是一种只存储一个副本的方法每个不同的字符串值,其中必须是不可变的.实习字符串做一些字符串处理任务更节省时间或空间需要更多时间的成本字符串被创建或实习.这不同的值存储在一个字符串中实习生池.

In computer science, string interning is a method of storing only one copy of each distinct string value, which must be immutable. Interning strings makes some string processing tasks more time- or space-efficient at the cost of requiring more time when the string is created or interned. The distinct values are stored in a string intern pool.

基本上,字符串实习生池允许运行时通过在池中保留不可变字符串来节省内存,以便应用程序的区域可以重用公共字符串的实例,而不是创建它的多个实例.

Basically, a string intern pool allows a runtime to save memory by preserving immutable strings in a pool so that areas of the application can reuse instances of common strings instead of creating multiple instances of it.

作为一个有趣的旁注,字符串实习是 flyweight 设计模式的一个例子:

As an interesting side note, string interning is an example of the flyweight design pattern:

Flyweight 是一种软件设计图案.享元是一个物体通过共享为最小化内存使用尽可能多的数据与其他相似的物体;这是一种使用方式当一个简单的对象大量重复表示将使用无法接受的内存量.

Flyweight is a software design pattern. A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory.

这篇关于什么是 Java 字符串池以及“s"如何与 new String("s") 不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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