我正在尝试从 Java Othello 程序中挤出所有内容,并且有一个点需要计算给定数字出现的实例数。例如 array[]{1,1,2,1,0,1} 将 count(1) 返回 4。下面是我通过计算所有数字来快速进行的尝试,但速度较慢:
public void count(int color) {
byte count[] = new byte[3];
for (byte i = 0; i < 64; i++)
++count[state[i]];
return count[color];
}
到目前为止,这是我测试过的最有效的代码:
public void count(int color) {
byte count = 0;
for (byte i = 0; i < 64; i++)
if (this.get(i) == color)
count++;
return count;
}
有人认为他们可以从中获得更多速度吗?我只需要指定数量的计数,仅此而已。
最佳答案
使用int
,不是byte
- 在内部,Java 将字节转换为 int,然后递增它,然后将其转换回字节;使用 int 消除了类型转换的需要。
您还可以尝试使用 AtomicInteger ,其 getAndIncrement
方法可能比 ++
更快运算符。
您还可以展开循环;这将减少 i < 64
的次数被评估。尝试使用 AtomicInteger i
,并使用getAndIncrement
而不是++
for(int i = 0; i < 64;) {
if(this.get(i++) == color) ...
if(this.get(i++) == color) ...
if(this.get(i++) == color) ...
if(this.get(i++) == color) ...
}
将for循环改为do-while循环可能会稍微快一点——for循环有条件跳转和无条件跳转,但do-while循环只有条件跳转。
您可以并行执行此操作(线程 1 计算元素 0-15,线程 2 计算元素 16-31 等),但创建线程的成本可能不值得。
关于java - 从数组中计算单个 int 的更有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16206331/