简体   繁体   English

String.length()是否为最终的String调用?

[英]Is String.length() invoked for a final String?

A quickie just to get peace of mind: 快速安心,让您高枕无忧:
Considering the following 考虑以下因素

final String str = "This is the end";

Is str.length() evaluated at runtime or is it hardcoded as 15 in the bytecode? str.length()是在运行时评估还是在字节码中硬编码为15?

str.length() is calculated in String constructor and saved in private final int count; str.length()String constructor计算并保存在private final int count; , str.length() just returns the count variable. str.length()只返回count变量。 I just checked the Source here http://www.docjar.com/html/api/java/lang/String.java.html 我刚刚查看了这里的来源http://www.docjar.com/html/api/java/lang/String.java.html

str.length() is evaluated at runtime. str.length()在运行计算。 final means that value of the reference cannot be changed. final表示不能更改引用的值。 It has nothing to do with the string itself. 它与字符串本身无关。

However, if you look into the source code of String you will see that length() returns the value of a field, so no computation takes place, the value os simply read... 但是,如果你查看String的源代码,你会看到length()返回一个字段的值,所以不进行任何计算,值os只是读取...

In the bytecode the method will be evaluated. 在字节码中,将评估该方法。

However, the method call will likely be inlined during jit compilation 但是,在jit编译期间可能会内联方法调用

The code for the String.length() method is as follows: String.length()方法的代码如下:

public int length() {
    return count;
}

I don't think the fact that the reference to the string is declared final has any bearing on the inlining in this case. 我不认为对字符串的引用被声明为final的事实与此情况下的内联有关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM