【发布时间】:2019-10-04 15:36:20
【问题描述】:
我在 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;
}
【问题讨论】:
-
什么是
readBytes?请发布其内容 -
readBytes == 字节大小[]
-
老实说,没有。没有更快的方法来做到这一点。它已经和汇编语言几乎一样了。
-
@VGR 你是说 JIT 能够产生一个 vectorized version ,像在汇编中一样一次比较 16+ 个字节?
-
@thatotherguy:一个好的 JIT 很有可能可以矢量化这个循环。
标签: java optimization