[英]TABLESWITCH Performance Increase?
Say I have the following switch
statement: 说我有以下
switch
语句:
switch (i)
{
case 0: ...; return ...;
case 1: ...; return ...;
case 2: ...; return ...;
case 400: ...; return ...;
case 401: ...; return ...;
case 402: ...; return ...;
}
Since the gaps are too large for the compiler to generate a reasonable TABLESWITCH
( O(1)
complexity) instruction here, it uses a LOOKUPSWITCH
( O(log n)
complexity). 由于间隙太大,编译器无法在此处生成合理的
TABLESWITCH
( O(1)
复杂度)指令,因此它使用LOOKUPSWITCH
( O(log n)
复杂度)。 Would it be possible to increase the performance of this code by splitting the switch
into two like this: 通过将
switch
拆分为两个,可以提高此代码的性能:
switch (i)
{
case 0: ...; return ...;
case 1: ...; return ...;
case 2: ...; return ...;
}
switch (i)
{
case 400: ...; return ...;
case 401: ...; return ...;
case 402: ...; return ...;
}
This would cause the compiler to generate two TABLESWITCH
instead of one LOOKUPSWITCH
. 这将导致编译器生成两个
TABLESWITCH
而不是一个LOOKUPSWITCH
。
Do not spend much time trying to optimize the bytecode. 不要花太多时间尝试优化字节码。 The bytecode does not necessarily reflect the performance of JIT-compiled methods.
字节码不一定反映JIT编译方法的性能。 Why don't you take JMH and check the actual performance of both cases yourself?
您为什么不选择JMH自己检查这两种情况的实际表现?
In fact, HotSpot C2 compiler treats tableswitch
and lookupswitch
in a similar way, and it takes care of lookupswitch
that has sequential labels with gaps very well. 实际上,HotSpot C2编译器以类似的方式处理
tableswitch
和lookupswitch
,并且它很好地处理了带有间隙的顺序标签的lookupswitch
。
Both cases are translated into a sequence of compare and conditional jump instructions in a binary search-like manner and work almost identically performance-wise. 两种情况都以类似于二进制搜索的方式转换为比较和条件跳转指令序列,并且在性能方面几乎相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.