想测试一下关于每个栈帧大小对于栈深度的影响。栈大小设置为-Xss160k
public class TestStack { public static int i; public static void main(String[] args) { test(); } public static void test(){ System.out.println(i++); test2(); } public static void test2(){ System.out.println(i++); test(); } }
这样跑的话,大概 i 跑出的数字到 830 就栈溢出了,所以我在每个方法中添加了变量,例如
public static void test2(){ int i1 =10000; int i2 =10000; int i3 =10000; int i4 =10000; int i5 =10000; System.out.println(i++); test(); }
而这样跑的话大概 i 跑到 560 左右就栈溢出了,随后我建了一个对象
class StackCount{ int i = 100000; int i2 = 100000; int i3 = 100000; int i4 = 100000; int i45= 100000; int i455= 100000; int i4555= 100000; }
方法改为如下
public static void test2(){ for (int j = 0; j < 100; j++) { StackCount stackCount = new StackCount(); } System.out.println(i++); test(); }
不断的在对象里面添加 int 属性的同时,栈深度也在不断的变小。
于是问题就来了,栈帧的大小为什么会随着对象大小变化呢?对象不是存放在堆内存中吗?栈帧不是只存放地址吗?
希望有大佬可以给解答一下。
1 cyspy 2019-05-23 15:27:55 +08:00 基本类型和对象的引用在栈上,另外还和调用的函数参数数量有关,栈帧大小是在编译期确定的 |