关于RandomAccessFile分段写入的速度问题

xperdit 2018-08-06 10:20:30
看如下代码

public class Test {

public static final int size = 1024*1024*200;
public static final int piecesCount = 200;

public static void main(String[] args) throws IOException, InterruptedException {
byte[] arr = new byte[size];
Random r = new Random();
for(int i = 0;i < size;i++){
arr[i] = (byte) (r.nextInt() >> 24);
}

RandomAccessFile file = new RandomAccessFile("test1","rw");
int pieceSize = size /piecesCount;
long startMs = System.currentTimeMillis();

for(int i = 0;i < piecesCount;i++){
file.write(arr,pieceSize * i,pieceSize);
}

System.out.println(System.currentTimeMillis() - startMs);
file.close();

file = new RandomAccessFile("test2","rw");

startMs = System.currentTimeMillis();
file.write(arr);
System.out.println(System.currentTimeMillis() - startMs);

file.close();

}


}

运行结果是

159
1780

Process finished with exit code 0

可见分段写入的速度是远远大于整块写入的,并且我做过多次试验,当piecesCount极大和极小的情况下速度都很慢,也就是说存在一个极值点使得写入速度最快。那么问题来了,是什么原因导致这个问题的,而为什么jdk不对这个方法做优化呢?
...全文
299 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
xperdit 2018-08-14
  • 打赏
  • 举报
回复
你想表明什么??我看了你分享的网页一头雾水。。。
verejava 2018-08-14
  • 打赏
  • 举报
回复
Java IO流 之 RandomAccessFile 多线文件拷贝

http://www.verejava.com/?id=16994721196019
xperdit 2018-08-13
  • 打赏
  • 举报
回复
怎么没人啊 !!!!!!

50,529

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧