首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么将数据写入磁盘的速度比将数据保存在内存中的速度快?

为什么将数据写入磁盘的速度比将数据保存在内存中的速度快?
EN

Stack Overflow用户
提问于 2014-07-31 14:36:30
回答 2查看 3.2K关注 0票数 18

我有以下10000000x2矩阵:

代码语言:javascript
运行
复制
0        0
1        1
2        2
..       ..
10000000 10000000

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

代码语言:javascript
运行
复制
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);
}

输出:

代码语言:javascript
运行
复制
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

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

代码语言:javascript
运行
复制
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);
}

输出:

代码语言:javascript
运行
复制
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

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

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25052263

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档