java - 从数组中计算单个 int 的更有效方法?

标签 java performance

我正在尝试从 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/

相关文章:

java - 我的 DataProvider 没有被调用

java - 使用Java数组的热图图像

java - 在android中显示区域字符

performance - tomcat7 中的 GZip 压缩在 IE9 中不起作用

sql-server - 使用键/对表与 XML 字段和 XPath 的 SQL Server 性能

Python:尝试除了 KeyError 与 if has_key()

java - 如何在 Windows Azure 上部署 Java 应用程序

java - 在 X1 y1 X2 y2 形式的 10,000 个点的文件中,如何检测至少 4 个形成正方形的点? java

python - 无请求时网站速度慢 + cpu 使用率高

performance - 分析 OpenGL 应用程序 - 当驱动程序阻塞 CPU 端时