如果未提供命令行参数,则 main()
中用于接受命令行参数的参数 String args[]
是否会产生影响。
是吗:
- 创建一个新的 String 对象?
- 是否为其分配了内存?
Java 遇到 String args[]
时会做什么?
更新: 想问一个相关的问题:如果没有提供 cmdline args,String args[] 将为空还是 null?
最佳答案
A String[] is an object and an empty one will be about 16 bytes.
That was helpful. How can I calculate that myself?
public static long memoryUsed() {
final Runtime rt = Runtime.getRuntime();
return rt.totalMemory() - rt.freeMemory();
}
public static void main(String... args) {
long before = memoryUsed();
String[] arr = { };
long after = memoryUsed();
if(before == after) throw new AssertionError("you need to turn off the TLAB with -XX:-UseTLAB");
System.out.printf("The String[] used %,d bytes of memory%n", (after - before));
}
打印
The String[] used 16 bytes of memory
注意:这会打印创建对象使用了多少内存。如果创建临时对象,这可能会超过保留的数量。
关于java - String args[] 参数是否创建 String 的新实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12276856/