我想在 Clojure 中使用以下代码快速将文件读入内存:
FileInputStream f = new FileInputStream( name );
FileChannel ch = f.getChannel( );
byte[] barray = new byte[SIZE];
ByteBuffer bb = ByteBuffer.wrap( barray );
long checkSum = 0L;
int nRead;
while ((nRead = ch.read(bb)) != -1) {
for (int i = 0; i < nRead; i++)
checkSum += barray[i];
bb.clear( );
}
代码来自:FileChannel with array ByteBuffer and byte array access
调用 Java 类构造函数和点方法非常简单,但是使用 Clojure 的 while
和 for
会导致显着的性能损失吗?尝试以最直接的方式转换 Clojure 有什么问题吗?
最佳答案
您必须使用dotimes
代替for
,使用loop..recur
代替while
。
但是,如果您真的追求性能,而不是阅读,我会内存映射 FileChannel
并从 ByteBuffer
创建一个 LongBuffer
以便读取字节八乘八。
关于Clojure 中带有 ByteBuffer 的 Java FileChannel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23878647/