Using dup for calculations in a Java method

谁说胖子不能爱 提交于 2019-12-11 13:18:06

问题


I currently have a method that does the follow: given: value, offset, stride, it adds offset to value keeping it within a group of size stride.
Examples:

20, 5, 30 => 25
29, 5, 30 => 4
42, 5, 30 => 47

And my current code is:

int cycle(int value, int offset, int stride) {
    final int rem = value % stride;
    return ((rem + offset) % stride - rem + value);
}

Which compiles to the following:

int cycle(int, int, int);
  Code:
     0: iload_1
     1: iload_3
     2: irem
     3: istore        4
     5: iload         4
     7: iload_2
     8: iadd
     9: iload_3
    10: irem
    11: iload         4
    13: isub
    14: iload_1
    15: iadd
    16: ireturn

Is there any combination of code changes and / or compiler options that can make it produce something like this instead? (The example was written by hand):

int cycle(int, int, int);
  Code:
     0: iload_1
     1: iload_3
     2: irem
     3: dup
     4: iload_2
     5: iadd
     6: iload_3
     7: irem
     8: isub
     9: iload_1
    10: iadd
    11: ireturn

回答1:


Most optimizing JVMs, most notably the commonly using HotSpot JVM, will transform the code into the SSA form before applying any other optimization. For this representation, it is entirely irrelevant whether the original code used temporary local variables or dup on the operand stack, the in­ter­me­di­ate representation will be the same.

So javac doesn’t offer any option to control the byte code representation of such a construct, but it doesn’t matter anyway.



来源:https://stackoverflow.com/questions/48629248/using-dup-for-calculations-in-a-java-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!