简体   繁体   English

方法中的局部变量如何计算Java字节码

[英]How are local variables in method counted java bytecode

I have been learning about java byte-code recently, and i have been understanding most of it, but i am confused about how the local variable count for example is counted. 我最近一直在学习Java字节码,并且已经了解了大多数,但是对于如何计算局部变量计数感到困惑。 I thought it would just be the total of the local variables, but this code generates 1 local variable when looking through the bytecode 我以为那只是局部变量的总数,但是当遍历字节码时,此代码会生成1个局部变量

public int testFail()
{
    return 1;
}

But i thought it should be zero local variables because no local variable are defined. 但是我认为应该是零局部变量,因为没有定义局部变量。

Additionally this method also generates one local variable but it has more local variables than the previous example. 此外,此方法还生成一个局部变量,但它比前面的示例具有更多的局部变量。

Finally this method 最后这个方法

public static int testFail(int a, int b)
{
    return a+b;
}

gnerates two local variable in the bytecode. 在字节码中生成两个局部变量。

public static int testFail(int a)
{
    return a;
}

Non-static methods use a local variable slot for this . 非静态方法this使用局部变量插槽。 Another complication is that long s and double s count as 2 each. 另一个复杂之处是long s和double s各自计为2。 Also, depending on your compiler and settings, you may not see a one-to-one mapping between local variables in the source code and local variables in the byte code. 另外,根据您的编译器和设置,您可能看不到源代码中的局部变量和字节码中的局部变量之间的一对一映射。 For example, if debug information is left out, the compiler may eliminate unnecessary local variables. 例如,如果省略了调试信息,则编译器可能会消除不必要的局部变量。

Edit: 编辑:

I just remembered: compilers may also re-use local variable slots. 我只记得:编译器可能还会重用局部变量插槽。 For example, given this code: 例如,给出以下代码:

public static void test() {
    for(int i = 0; i < 100; i++) {
        ...
    }
    for(int j = 0; j < 100; j++) {
    }
}

the same slot can be used for i and j because their scopes don't overlap. 相同的插槽可用于ij因为它们的范围不重叠。

第一个具有局部变量的原因是因为它是一种非静态方法,所以存在一个隐式的this参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM