在 Java 方法中使用 dup 进行计算 [英] Using dup for calculations in a Java method

查看:21
本文介绍了在 Java 方法中使用 dup 进行计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个方法可以执行以下操作:给定:值,偏移量,步幅,它将偏移量添加到值中,使其保持在一组大小步幅内.
示例:

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

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

而我目前的代码是:

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

编译如下:

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

推荐答案

大多数优化 JVM,尤其是常用的 HotSpot JVM,会将代码转换为 SSA 表单.对于这种表示,原始代码是使用临时局部变量还是操作数堆栈上的dup完全无关,中间表示将是相同的.

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.

所以 javac 没有提供任何选项来控制这种结构的字节码表示,但无论如何都无所谓.

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

这篇关于在 Java 方法中使用 dup 进行计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆