gpt4 book ai didi

java - 为什么将数据写入磁盘与将数据保存在内存中一样快?

转载 作者:太空狗 更新时间:2023-10-29 22:34:00 29 4
gpt4 key购买 nike

我有以下 10000000x2 矩阵:

0        0
1 1
2 2
.. ..
10000000 10000000

现在我想将这个矩阵保存到 int[][] 数组中:

import com.google.common.base.Stopwatch;

static void memory(int size) throws Exception {
System.out.println("Memory");

Stopwatch s = Stopwatch.createStarted();

int[][] l = new int[size][2];
for (int i = 0; i < size; i++) {
l[i][0] = i;
l[i][1] = i;
}

System.out.println("Keeping " + size + " rows in-memory: " + s.stop());
}

public static void main(String[] args) throws Exception {
int size = 10000000;
memory(size);
memory(size);
memory(size);
memory(size);
memory(size);
}

输出:

Keeping 10000000 rows in-memory: 2,945 s
Keeping 10000000 rows in-memory: 408,1 ms
Keeping 10000000 rows in-memory: 761,5 ms
Keeping 10000000 rows in-memory: 543,7 ms
Keeping 10000000 rows in-memory: 408,2 ms

现在我想将这个矩阵保存到磁盘:

import com.google.common.base.Stopwatch;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;

static void file(int size, int fileIndex) throws Exception {
Stopwatch s = Stopwatch.createStarted();

FileOutputStream outputStream = new FileOutputStream("D:\\file" + fileIndex);
BufferedOutputStream buf = new BufferedOutputStream(outputStream);
for (int i = 0; i < size; i++) {
buf.write(bytes(i));
buf.write(bytes(i));
}

buf.close();
outputStream.close();

System.out.println("Writing " + size + " rows: " + s.stop());
}

public static void main(String[] args) throws Exception {
int size = 10000000;
file(size, 1);
file(size, 2);
file(size, 3);
file(size, 4);
file(size, 5);
}

输出:

Writing 10000000 rows: 715,8 ms
Writing 10000000 rows: 636,6 ms
Writing 10000000 rows: 614,6 ms
Writing 10000000 rows: 598,0 ms
Writing 10000000 rows: 611,9 ms

不应该更快地保存到内存中吗?

最佳答案

正如评论中所说,您没有衡量任何有用的东西。 JVM 将写操作缓存在其内存中,然后将其刷新到操作系统,操作系统将其缓存在内存中,然后在某个时刻最终将其写入磁盘。
但是您只是在测量 JVM 将其缓存在自己的内存中所花费的时间(这是您可以测量的全部)。

无论如何,您不应该为这种微观优化而烦恼。

关于java - 为什么将数据写入磁盘与将数据保存在内存中一样快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25052263/

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