`

一些简单的java字节码

阅读更多
java字节码 是与机器无关的代码,由Java编译器生成,Java解释器来执行。
先来一个程序看看会生成些什么字节码.
public static int preIncrement() {
  int i = 0, j;
  j = ++i;
  return j;
}
public static int postIncrement() {
  int i = 0, j;
  j = i++;
  return j;
}

用javap -c [类名] 命令看一下会生成些什么字节码.用 lvar 表示局部变量表,就像它是一个 Java 数组
Method int preIncrement()
   0 iconst_0     //push 0 onto the stack
   1 istore_0     //pop 0 from the stack and store it at lvar[0], i.e. lvar[0]=0
   2 iinc 0 1     //lvar[0] = lvar[0]+1 which means that now lvar[0]=1
   5 iload_0      //push lvar[0] onto the stack, i.e. push 1
   6 istore_1     //pop the stack (value at top is 1) and store at it lvar[1], i.e. lvar[1]=1
   7 iload_1      //push lvar[1] onto the stack, i.e. push 1
   8 ireturn      //pop the stack (value at top is 1) to the invoking method i.e. return 1
Method int postIncrement()
   0 iconst_0     //push 0 onto the stack
   1 istore_0     //pop 0 from the stack and store it at lvar[0], i.e. lvar[0]=0
   2 iload_0      //push lvar[0] onto the stack, i.e. push 0
   3 iinc 0 1     //lvar[0] = lvar[0]+1 which means that now lvar[0]=1
   6 istore_1     //pop the stack (value at top is 0) and store at it lvar[1], i.e. lvar[1]=0
   7 iload_1      //push lvar[1] onto the stack, i.e. push 0
   8 ireturn      //pop the stack (value at top is 0) to the invoking method i.e. return 0


<table border="1" cellpadding="3" cellspacing="0" width="100%">
<tr align="left" valign="middle">
<td><b>字节码</b></td>
<td><b>描述</b></td>
</tr>
<tr>
<td>iconst_0</td>
<td>将 0 推到堆栈中</td>
</tr>
<tr>
<td>iconst_1</td>
<td>将 1 推到堆栈中</td>
</tr>
<tr>
<td>istore_0</td>
<td>从堆栈中弹出这个值,并将它存储到局部变量表的索引 0 处</td>
</tr>
<tr>
<td>istore_1</td>
<td>从堆栈中弹出这个值,并将它存储到局部变量表的索引 1 处</td>
</tr>
<tr>
<td>iload_0</td>
<td>将局部变量表索引 0 处的值推到堆栈中</td>
</tr>
<tr>
<td>iload_1</td>
<td>将局部变量表索引 1 处的值推到堆栈中</td>
</tr>
<tr>
<td>iadd</td>
<td>从操作数堆栈中弹出两个整数并让它们相加。将得到的整数推回堆栈中</td>
</tr>
<tr>
<td>iinc 0 1</td>
<td>局部变量表索引 0 处的变量加 1</td>
</tr>
<tr>
<td>ireturn</td>
<td>从堆栈中弹出值并将它推到调用方法的操作数栈中。退出方法</td>
</tr>
</table>



//////////////////////////////////////////////
1.字节码主要涉及两个东西,第一是堆栈,第二是局部变量表.
2.堆栈是后进先出,如是赋值等操作都是先要压进堆栈再弹出,这样做的.变量自己加1,像iinc 0 1 ;这样就可以在局部变量表中完成.
3.命令
栈的
iconst_0 ,把常量0压进堆栈,i代表int类型,const常量意思,0是值.
istort_0 ,从堆栈顶弹出并保存到局部变量表的0位置,lvar[0]=栈顶.i代表int,stort保存,0值.
ireturn ,从堆栈中弹出值并将它推到调用方法的操作数栈中。退出方法.i代表int
变量表的
iload_0 ,局部变量表,索引0的压进堆栈.0代表变量表中的位置.
iinc 0 1 ,索引位置加0的值加1.
4.索引表的位置

int i,j,k;

索引表位置i是lvar[0],j是lvar[1],k是lvar[2].
参考:
关注性能: 宏性能基准测试 http://www.ibm.com/developerworks/cn/java/j-perf12053/index.html
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics