java - 显着优化 for 循环中的字节操作(通过避免循环?)

标签 java android performance for-loop bit-manipulation

我必须应用到我的流位操作和算术操作的每个字节。

我将代码示例中的 for 循环确定为输出流的瓶颈,并希望对其进行优化。我只是没有想法 ;)

    private static final long A = 0x1ABCDE361L;
    private static final long C = 0x87;
    private long x;

     //This method belongs to a class that extends java.io.FilteredOutputStream 
    @Override
    public void write(byte[] buffer, int offset, int length) throws IOException {
        for (int i = 0; i < length; i++) {
            x = A * x + C & 0xffffffffffffL;
            buffer[offset + i] = 
                        (byte) (buffer[offset + i] ^ (x>>>16));
        }

        out.write(buffer, offset, length);
    }   

该代码主要用于 Android 设备。

更新

我希望将执行时间至少缩短 50%。我从我的 CRC32 基准测试中了解到 CRC32#update(byte[] b, int off, int len)CRC32#update(byte b) 快十倍在大于 30 字节的 block 上。 (我的 block 大于 4096 字节)所以,我想我需要一些可以同时处理数组的实现。

最佳答案

下面的代码在 32 位 cpus 上会快一点:

private static final long A = 0x1ABCDE361L;
private static final long C = 0x87;
private long x;

//This method belongs to a class that extends java.io.FilteredOutputStream
@Override
public void write(byte[] buffer, int offset, int length) throws IOException {
    for (int i = 0; i < length; i++) {
        x = A * x + C;
        buffer[offset + i] = (byte) (buffer[offset + i] ^ ((int)x>>>16));
    }

    out.write(buffer, offset, length);
}   

由于将 x 右移 16 位并将异或运算结果转换为 byte,实际上只有 16 位到 23 位. 用于 x,因此它可以在右移操作之前转换为 32 位,从而使两个操作在 32 位 cpus 上更快。

关于java - 显着优化 for 循环中的字节操作(通过避免循环?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38392994/

相关文章:

java - 用于 HTTPS 抓取的 Jsoup Cookie

java - 嵌套在接口(interface)中的类

java - 在 Android 设备上将在线数据导入 SQLite 数据库的推荐文件/文件类型

android - GridView 吃掉我的 onTouch 事件并开始 "scrolling"

c# - Windows 窗体应用程序的性能测试

performance - 自定义映射器和 Reducer 与 HiveQL

c# - 通过 Equals 或 HashCode 进行比较。哪个更快?

java - 使用 Rest CXF 管理异常

java - 提取数组元素以分离数组

android - 模块依赖 - Android Studio