在这段代码中,每次我调用 goodMethod() 时,它都会使用在堆空间中创建的唯一对象和静态字。
我的问题是:当我调用 badMethod() 时,是否会在每次调用此方法时在堆空间中创建一个新的 String 对象?因此,如果我调用我的方法 1_200_000 次,它是否会在堆空间中创建 1_200_000 字符串对象?
毫无疑问,第一种方法更好(为了代码的可读性和可维护性)。我只是在这里询问内存中创建的对象数量
谢谢
我在谷歌上阅读了很多关于此的内容,但没有找到带有论点或证据的回复。如果你知道我如何测试这个,也请谢谢分享。
public class Main {
private static final String HELLO = "hello";
private static final String WORLD = "world";
public static void main(String[] args) {
for (int i = 0; i < 1_200_000; i++) {
goodMethod();
badMethod();
}
}
private static void goodMethod(){
System.out.println(HELLO);
System.out.println(WORLD);
}
private static void badMethod(){
System.out.println("hello");
System.out.println("world");
}
}
// an other example
Map<String, Object> map = new HashMap<>();
map.put("myKey", xxx.getYYY()); …Run Code Online (Sandbox Code Playgroud)