这是java可以做而c不能做的吗?
Is this what java can do and c can't?
当我们在Java中使用像a = new int[n]
这样的动态数组时,n
是传递给方法的参数,Java可以使用逃逸分析并分配这个堆栈而不是堆上的动态长度数组? c 能做到吗?我的意思是 C 可以在堆栈上分配动态长度数组还是必须在堆栈上?这是 Java 比 C 更好的地方吗?
理论上 Java 可以在运行时决定是否在栈上分配(基于Escape分析,如果需要的分配低于特定阈值)或在堆上分配。
不过这是理论上的。要检查您的 JVM 是否对非常量值进行了此优化,您可以按照以下 SO answer 中建议的测试进行操作
another question on Escape Analysis in Java.
- HotSpot JVM 根本不做 "on stack allocation"。相反,它具有 Scalar Replacement 优化。
- HotSpot JVM 可以 将标量替换应用于数组,但前提是长度是 常数 不大于
EliminateAllocationArraySizeLimit
(默认等于 64),见 escape.cpp:
if (call->is_AllocateArray()) {
if (!cik->is_array_klass()) { // StressReflectiveCode
es = PointsToNode::GlobalEscape;
} else {
int length = call->in(AllocateNode::ALength)->find_int_con(-1);
if (length < 0 || length > EliminateAllocationArraySizeLimit) {
// Not scalar replaceable if the length is not constant or too big.
scalar_replaceable = false;
}
}
当我们在Java中使用像a = new int[n]
这样的动态数组时,n
是传递给方法的参数,Java可以使用逃逸分析并分配这个堆栈而不是堆上的动态长度数组? c 能做到吗?我的意思是 C 可以在堆栈上分配动态长度数组还是必须在堆栈上?这是 Java 比 C 更好的地方吗?
理论上 Java 可以在运行时决定是否在栈上分配(基于Escape分析,如果需要的分配低于特定阈值)或在堆上分配。
不过这是理论上的。要检查您的 JVM 是否对非常量值进行了此优化,您可以按照以下 SO answer 中建议的测试进行操作 another question on Escape Analysis in Java.
- HotSpot JVM 根本不做 "on stack allocation"。相反,它具有 Scalar Replacement 优化。
- HotSpot JVM 可以 将标量替换应用于数组,但前提是长度是 常数 不大于
EliminateAllocationArraySizeLimit
(默认等于 64),见 escape.cpp:
if (call->is_AllocateArray()) {
if (!cik->is_array_klass()) { // StressReflectiveCode
es = PointsToNode::GlobalEscape;
} else {
int length = call->in(AllocateNode::ALength)->find_int_con(-1);
if (length < 0 || length > EliminateAllocationArraySizeLimit) {
// Not scalar replaceable if the length is not constant or too big.
scalar_replaceable = false;
}
}