java - 两个数字之间的 "compare"如何在机器级别实现?

标签 java optimization assembly comparison low-level

首先,这个问题与 for 无关循环性能。这只是背景。

所以,我不知何故发现,在使用Java时,向下计数for循环比向上计数循环快得多。我的意思是,for(int i=0; i < n; i++)for(int i=n-1; i >=0; i++) 慢得多。 (是的,我确实知道过早优化是万恶之源,但我只是想找出原因)。所以,这让我认为差异是因为cmp是用机器级语言实现的。我能想到的关于写作的方法之一compare函数本身是这样的:

public int compare(int a, int b) {
  int diff = a-b;
  if(diff == 0) {
    return 0;
  }
  if(b ==0) {
    return((is MSD of a 1)?-1:1);
  }
  return(diff,0);
} 

我可以通过按位机大小右移数字来检查 MSD 位,看看它是 1 还是 0。但是,即使如此,我也需要 == 。这又会回到同样的问题。所以,我的问题是,在 assembly 或机器级别,<,>,== 怎么样?仅使用按位运算实现,也许 jmp序列?

最佳答案

for(int i=0; i < n; i++) is way slower than for(int i=n-1; i >=0; i++)

不,不是。在被 JITC 优化之前,它只会变慢。写一个CaliperJMH基准测试来查看这一点(我不久前做过)。否则,您很可能会得到完全无意义的结果(是的,Java 基准测试确实很难)。

So, this led me to think that the difference is because of how cmp is implemented in machine-level language.

没有cmp在后一个循环中。它看起来就像(类似 Java 的语法)

i--;
if (!zero_flag) goto loop_start;

这就是性能优势的来源。

One of the ways I could think of regarding writing compare function natively is like this

不,没有这样的事情。大多数 CPU 上都有 cmp指令的工作方式就像 sub ,但无处写出差异。它只设置标志(零、进位、负数……),这正是下面的条件跳转所使用的。

所有有意义的标志组合都是 implemented ,即,您可以执行任何条件 a < b , a <= b , .... 使用单个指令。

how are <,>,== implemented just using bitwise operations and maybe jmp sequences?

一点也不。那里没有任何麻烦。

关于java - 两个数字之间的 "compare"如何在机器级别实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28123617/

相关文章:

java - 使用cardLayout时JPanel不会显示paintComponent

java - org.springframework.beans.factory.UnsatisfiedDependencyException org.springframework.beans.factory.NoUniqueBeanDefinitionException

mysql - 持久mysql连接,无论用户连接如何?

c - 防止使用数据段(优化复制)到本地堆栈数据结构/数组

java - 以编程方式获取 LOV 的所有返回值

java - Google 身份验证找不到 .p12 文件

xslt - 第一个元素的特定模板

c - 内存依赖推测是否会阻止 BN_consttime_swap 成为恒定时间?

c - 我如何绕过返回地址覆盖而不是重定向控制流?

assembly - 引导加载程序加载自身而不是内核