问题描述
我写了两种检查性能的方法
I wrote two methods to check there performance
public class Test1 {
private String value;
public void notNull(){
if( value != null) {
//do something
}
}
public void nullNot(){
if( null != value) {
//do something
}
}
}
并在编译后检查它的字节代码
and checked it's byte code after compiling
public void notNull();
Code:
Stack=1, Locals=1, Args_size=1
0: aload_0
1: getfield #2; //Field value:Ljava/lang/String;
4: ifnull 7
7: return
LineNumberTable:
line 6: 0
line 9: 7
StackMapTable: number_of_entries = 1
frame_type = 7 /* same */
public void nullNot();
Code:
Stack=2, Locals=1, Args_size=1
0: aconst_null
1: aload_0
2: getfield #2; //Field value:Ljava/lang/String;
5: if_acmpeq 8
8: return
LineNumberTable:
line 12: 0
line 15: 8
StackMapTable: number_of_entries = 1
frame_type = 8 /* same */
}
在这里,两个操作码用于实现if条件:在第一种情况下,它使用ifnull-检查堆栈的最高值为null-,在第二种情况下,它使用if_acmpeq-检查前两个值在堆栈中是相等的 -
in here two opcodes are used to implement the if condition: in first case it use ifnull- check top value of stack is null-, and in second case it use if_acmpeq- check top two value are equal in the stack-
那么,这会对性能产生影响吗?
(这将有助于我证明null的首次实现在性能方面以及在可读性方面都很好:))
so, will this make an effect on performance?(this will helps me to prove first implementation of null is good in performance wise as well as in the aspect of readability :) )
推荐答案
比较生成的字节码几乎没有意义,因为大多数优化都是在运行时使用JIT编译器进行的。我猜想在这种情况下,表达式同样快。如果存在任何差异,则可以忽略不计。
Comparing the generated bytecodes is mostly meaningless, since most of the optimization happens in run time with the JIT compiler. I'm going to guess that in this case, either expression is equally fast. If there's any difference, it's negligible.
这不是您需要担心的事情。寻找大图优化。
This is not something that you need to worry about. Look for big picture optimizations.
这篇关于'...!= null'或'null!= ....'最佳表现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!