如您所知,Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE为了防止出现负值,该safeAbs方法在我的项目中实现了:
public static int safeAbs(int i) {
i = Math.abs(i);
return i < 0 ? 0 : i;
}
我将性能与以下性能进行了比较:
public static int safeAbs(int i) {
return i == Integer.MIN_VALUE ? 0 : Math.abs(i);
}
第一个几乎比第二个慢 6 倍(第二个性能几乎与“纯”Math.abs(int) 相同)。从我的角度来看,字节码没有显着差异,但我猜差异存在于 JIT“汇编”代码中:
“慢”版本:
0x00007f0149119720: mov %eax,0xfffffffffffec000(%rsp)
0x00007f0149119727: push %rbp
0x00007f0149119728: sub $0x20,%rsp
0x00007f014911972c: test %esi,%esi
0x00007f014911972e: jl 0x7f0149119734
0x00007f0149119730: mov %esi,%eax
0x00007f0149119732: jmp 0x7f014911973c
0x00007f0149119734: neg %esi
0x00007f0149119736: test %esi,%esi
0x00007f0149119738: jl 0x7f0149119748
0x00007f014911973a: mov %esi,%eax
0x00007f014911973c: add $0x20,%rsp
0x00007f0149119740: pop %rbp
0x00007f0149119741: test %eax,0x1772e8b9(%rip) ; {poll_return}
0x00007f0149119747: retq
0x00007f0149119748: mov %esi,(%rsp)
0x00007f014911974b: mov $0xffffff65,%esi
0x00007f0149119750: nop
0x00007f0149119753: callq 0x7f01490051a0 ; OopMap{off=56}
;*ifge
; - math.FastAbs::safeAbsSlow@6 (line 16)
; {runtime_call}
0x00007f0149119758: callq 0x7f015f521d20 ; {runtime_call}
Smart猫小萌
相关分类