我正面临一个困惑,希望有人能回答。请看下面的代码
for(int i = 0; i < 40; i++){
if(i < 20){ //Does this 20 here is initialized again and again
System.out.println("less than 20");
}else{
System.out.println("greater than 20");
}
}
所以我的问题是:i < 20 中的 20 是否一次又一次地初始化为整数,导致一次又一次地分配内存,或者 java 是否使用类似的概念,如 STRING POOL 它用于字符串。
据了解这需要内存,但我还是想确定一下。原因是:
我正在编写一个性能密集型代码,因此我无法在其中添加条件代码。像下面这样的东西
for(int p = 0; p < 10; p++){
if(p < 20){
System.out.println("ABC");
}
if(p < 20 && "SomeValue".equals("SomeValue")){
System.out.println("SomeValue");
}
if(p < 20 && "ABC".equals("ABC")){
System.out.println("ABCDEF");
}
}
因此,如果答案是肯定的,即 20 正在占用内存,那么我可以编写如下代码
int value = ("Coldrink".equals("coca cola"))?10:20;
for(int p = 0; p < 10; p++){
if(p < value){
System.out.println("ABC");
}
if(p < value && "SomeValue".equals("SomeValue")){
System.out.println("SomeValue");
}
if(p < value && "ABC".equals("ABC")){
System.out.println("ABCDEF");
}
}
正如您所看到的,变量值被初始化了一次,我已经提出了我自己的条件,这可能会有一些性能问题,但后来我减少了内存消耗,这可能会使事情变得更平衡。
编辑:感谢@T.J Crowder 消除了我的困惑。有相同问题的人请阅读已接受的答案以及Click on this resource too
最佳答案
Does the
20
ini < 20
gets initialized to an integer again and again causing allocation of memory again and again or does java uses similar kind of concept like a STRING POOL it uses for string.
都没有。 20
是原始的 int
值 — 不是 Integer
实例——在字节码中硬编码并加载到寄存器中以进行比较操作。不需要像字符串实习生池这样的东西,也不需要为每次迭代分配新的内存。
我们可以通过将循环放在 main
中看到这一点在示例类中:
public class Example {
public static void main(String[] args) {
for(int i = 0; i < 40; i++){
if(i < 20){ //Does this 20 here is initialized again and again
System.out.println("less than 20");
}else{
System.out.println("greater than 20");
}
}
}
}
...然后编译它,并通过 javap -c Example
查看字节码:
Compiled from "Example.java" public class Example { public Example(); Code: 0: aload_0 1: invokespecial #1 // Method java/lang/Object."":()V 4: return public static void main(java.lang.String[]); Code: 0: iconst_0 1: istore_1 2: iload_1 3: bipush 40 5: if_icmpge 39 8: iload_1 9: bipush 20 11: if_icmpge 25 14: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream; 17: ldc #3 // String less than 20 19: invokevirtual #4 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 22: goto 33 25: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream; 28: ldc #5 // String greater than 20 30: invokevirtual #4 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 33: iinc 1, 1 36: goto 2 39: return }
注意偏移量 9 和 11 处的粗体操作。
关于java - java在使用整数/ double / float 的情况下是否使用内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43208325/