gpt4 book ai didi

java - 如何更快地搜索 byte[] 中的字节?

转载 作者:行者123 更新时间:2023-12-02 01:17:52 24 4
gpt4 key购买 nike

我在InputStream中进行简单的行号计算(计算NewLines #10的数量)

for (int i = 0; i < readBytes ; i++) {
if ( b[ i + off ] == 10 ) { // New Line (10)
rowCount++;
}
}

我可以做得更快吗?不迭代一个字节?也许我正在寻找一些能够使用 CPU 特定指令(simd/sse)的类。

所有代码:

@Override
public int read(byte[] b, int off, int len) throws IOException {

int readBytes = in.read(b, off, len);

for (int i = 0; i < readBytes ; i++) {
hadBytes = true; // at least once we read something
lastByteIsNewLine = false;
if ( b[ i + off ] == 10 ) { // New Line (10)
rowCount++;
lastByteIsNewLine = (i == readBytes - 1); // last byte in buffer was the newline
}
}

if ( hadBytes && readBytes == -1 && ! lastByteIsNewLine ) { // file is not empty + EOF + last byte was not NewLine
rowCount++;
}

return readBytes;
}

最佳答案

在我的系统上,只需将 lastByteIsNewLinehasBytes 部分移出循环即可带来约 10% 的改进*:

  public int read(byte[] b, int off, int len) throws IOException {

int readBytes = in.read(b, off, len);

for (int i = 0; i < readBytes ; i++) {
if ( b[ i + off ] == 10 ) {
rowCount++;
}
}
hadBytes |= readBytes > 0;
lastByteIsNewLine = (readBytes > 0 ? b[readBytes+off-1] == 10 : false);

if ( hadBytes && readBytes == -1 && ! lastByteIsNewLine ) {
rowCount++;
}

return readBytes;
}

* 从填充任意文本的 ByteArrayInputStream 读取 10MB 缓冲区,进行 1,000 次迭代时分别为 6000 毫秒和 6700 毫秒。

关于java - 如何更快地搜索 byte[] 中的字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58239483/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com