Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从文件加载大2D int数组的最快方法是什么?_Java_Performance - Fatal编程技术网

Java 从文件加载大2D int数组的最快方法是什么?

Java 从文件加载大2D int数组的最快方法是什么?,java,performance,Java,Performance,我正在从文件中加载一个2D数组,它有15000000*3整数大(最终将是40000000*3)。现在,我使用dataInputStream.readInt()顺序读取int。大约需要15秒。我可以让它显著地(至少3倍)快一点吗?或者这是我能达到的最快速度吗?将您的文件映射到内存中 Java 7代码: FileChannel channel = FileChannel.open(Paths.get("/path/to/file"), StandardOpenOption.READ); B

我正在从文件中加载一个2D数组,它有15000000*3整数大(最终将是40000000*3)。现在,我使用
dataInputStream.readInt()
顺序读取int。大约需要15秒。我可以让它显著地(至少3倍)快一点吗?或者这是我能达到的最快速度吗?

将您的文件映射到内存中

Java 7代码:

FileChannel channel = FileChannel.open(Paths.get("/path/to/file"), 
    StandardOpenOption.READ);
ByteBuffer buf = channel.map(0, channel.size(),
    FileChannel.MapMode.READ_ONLY);

// use buf
有关更多详细信息,请参阅

如果使用Java 6,则必须:

RandomAccessFile file = new RandomAccessFile("/path/to/file", "r");
FileChannel channel = file.getChannel();
// same thing to obtain buf

如果需要,您甚至可以在缓冲区上使用
.asIntBuffer()
。当你需要阅读时,你只能阅读你真正需要阅读的内容。而且它不会影响您的堆。

是的,您可以。来自:

如果您必须选择最快的方法,可以选择以下方法之一:

  • FileChannel
    带有
    MappedByteBuffer
    和数组读取
  • FileChannel
    带有直接的
    ByteBuffer
    和数组读取
  • FileChannel
    带有包装数组
    ByteBuffer
    和直接数组访问
要获得最佳Java读取性能,需要记住4件事:

  • 通过一次读取一个数组而不是一个字节来最小化I/O操作 时间。8KB数组的大小很好(这就是为什么它是
    BufferedInputStream
    的默认值)
  • 通过一次获取一个数组而不是一个字节的数据来最小化方法调用 每次。使用数组索引获取数组中的字节
  • 如果不需要线程同步,则最小化线程同步锁 安全性。要么对线程安全类进行较少的方法调用,要么使用 非线程安全类,如
    FileChannel
    MappedByteBuffer
  • 最小化JVM/OS、内部缓冲区和 应用程序阵列。使用带有内存映射的
    FileChannel
    ,或直接 或包装数组
    ByteBuffer

想想阵列在内存中的布局。内存是1D…@HovercraftFullOfEels我当然在缓冲:)40 mil*3 int*4字节/int=480 MB。你的硬盘读取这么多数据的速度有多快?@Lyth抱歉,是15 mil(179 MB),我更新了问题,下载完所有数据后将是40 mil。你为什么不使用
MappedByteBuffer
?这也是一个很好的答案,如果我能接受两个答案,我会的。