我今天遇到了一件关于 RandomAccessFile
的有趣的事情。 .
我注意到使用 RandomAccessFile
的writeInt(int i)
方法比使用 RandomAccessFile
慢得多的write(byte[] b)
我首先将 int 值转换为 byte[4] 数组。
我正在使用此代码进行转换
private static byte[] intToByte(int i)
{
byte[] result = new byte[4];
result[0] = (byte) (i >> 24);
result[1] = (byte) (i >> 16);
result[2] = (byte) (i >> 8);
result[3] = (byte) (i);
return result;
}
差异非常显着,有利于write(byte[] b)
。
写作100万 int
我的笔记本电脑上安装了 JDK 8:
- 通过
writeInt(int i)
方法花费了~9秒 - 通过
write(byte[] b)
花了~2.3秒
我在另一个环境中得到了类似的结果,我使用的是 JDK 7 和完全不同的机器。
writeInt(int i) 方法委托(delegate)给原生 write0(int b)
方法和write(byte[] b)
代表原生writeBytes
.
当我进行分析时,我注意到大部分执行时间都花在 writeInt
上。使用时的方法。
有谁知道为什么我看到这么大的差异?看起来像writeInt
效率低得多。
最佳答案
RandomAccessFile 实际上有两个本地方法来写入字节:
//writes an array
private native void writeBytes(byte b[], int off, int len) throws IOException;
和
//writes one byte
public native void write(int b) throws IOException;
方法writeInt(int)使用 native write(int)方法单独写入每个字节,而write(byte[])使用 native writeBytes(byte[],int,int) 方法。
writeInt 方法执行 4 次方法调用来写入传递的整数值的每个字节,另一个方法仅使用一次调用来写入数组。在 Java 中,方法调用实际上是昂贵的操作:对于每次调用,JVM 都会为操作数堆栈和局部变量数组分配额外的内存。
关于java - RandomAccessFile writeInt(int i) 与 write(byte[] b) - 性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48630758/