gpt4 book ai didi

java - 对字符串使用静态变量

转载 作者:搜寻专家 更新时间:2023-10-31 19:31:26 25 4
gpt4 key购买 nike

以下内容摘自 Best practice: Writing efficient code但我不明白为什么

private static String x = "example";

private static final String x ="example";

谁能解释一下。

Using static variables for Strings

When you define static fields (also called class fields) of type String, you can increase application speed by using static variables (not final) instead of constants (final). The opposite is true for primitive data types, such as int.

For example, you might create a String object as follows:

private static final String x = "example";

For this static constant (denoted by the final keyword), each time that you use the constant, a temporary String instance is created. The compiler eliminates "x" and replaces it with the string "example" in the bytecode, so that the BlackBerry® Java® Virtual Machine performs a hash table lookup each time that you reference "x".

In contrast, for a static variable (no final keyword), the String is created once. The BlackBerry JVM performs the hash table lookup only when it initializes "x", so access is faster.

private static String x = "example";

You can use public constants (that is, final fields), but you must mark variables as private.

最佳答案

我不知道这一点,但它对我来说很有意义:

JVM 有一个内部字符串文字缓存。每次您使用文字创建字符串时,JVM 都必须在缓存中查找它,如果不存在,则存储它。

现在编译器可以使用 String 文字内联最终变量,因为它在编译时是已知的,而且这似乎是提高性能的好主意。

所以你的代码:

static final String CONST = "myconst";
...
if (CONST.equals(aVar))
...
case CONST
...

被编译器重写为:

static final String CONST = "myconst";
...
if ("myconst".equals(aVar))
...
case "myconst"
...

如果 JVM 实现不够聪明,在这个例子中它需要查找 3 次“myconst”。

当您不将 CONST 标记为“final”时,编译器无法“优化”它,因为该变量可以在运行时更改。您的代码将按 1:1 编译,JVM 只需要在变量中查找对象。

顺便说一句:糟糕的 JVM 实现不应该定义您的编码风格。 "final"提供了很多安全性,所以只要它不会真正影响您的性能:不要关心它是否会提高或降低您的速度 - 无论如何它对于下一个 JVM 来说是不同的

关于java - 对字符串使用静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2802032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com