本文介绍了为什么此代码带有多个“或"?语句比在Java中使用查找表快一点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在查看我昨天提出的微优化问题时(),我发现了一个奇怪的现象:Java中的or语句运行的速度 比在布尔数组中查找布尔值要快.

While looking at a micro-optimization question that I asked yesterday (here), I found something strange: an or statement in Java is running slightly faster than looking up a boolean value in an array of booleans.

在我的测试中,对long值(从0到10亿)运行以下算法,alg1快约2%. (我改变了算法测试的顺序,并且得到了相同的结果).我的问题是:为什么alg1会更快?我希望alg2会更快一些,因为它使用了查找表,而alg1必须对75%的输入执行4个比较和3个或操作. /p>

In my tests, running the below algorithms on long values from 0 to 1 billion, alg1 is about 2% faster. (I have altered the order in which the algorithms are tested, and I get the same results). My question is: Why is alg1 faster? I would have expected alg2 to be slightly faster since it uses a lookup table, whereas alg1 has to execute 4 comparisons and 3 or operations for 75% of inputs.

private final static boolean alg1(long n)
{
  int h = (int)(n & 0xF);
  if(h == 0 || h == 1 || h == 4 || h == 9)
  {
    long tst = (long)Math.sqrt(n);
    return tst*tst == n;
  }  
  return false;

}

private final static boolean[] lookup = new boolean[16];
static
{
  lookup[0] = lookup[1] = lookup[4] = lookup[9] = true;
}
private final static boolean alg2(long n)
{
  if(lookup[(int)(n & 0xF)])
  {
    long tst = (long)Math.sqrt(n);
    return tst*tst == n;
  }
  else
    return false;
}

如果您好奇的话,此代码将测试数字是否是一个完美的平方,并利用一个事实,即完美的平方必须以0、1、4或9十六进制结尾.

推荐答案

加载一些随机数据通常比一些非分支代码要慢.

Loading some random piece of data is generally slower than a little non-branching code.

当然,这全取决于处理器体系结构.您的第一个if语句可以实现为四个指令.第二种可能需要空指针检查,边界检查以及加载和比较.同样,更多的代码意味着更多的编译时间,以及更多以某种方式阻碍优化的机会.

It all depends upon processor architecture, of course. Your first if statement could be implemented as four instructions. The second may potentially need null pointer checking, bounds checking as well as the load and compare. Also more code means more compile time, and more chance for the optimisation to be impeeded in some manner.

这篇关于为什么此代码带有多个“或"?语句比在Java中使用查找表快一点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 09:47