测试发现NIO性能没有FileWriter好!

铁衣 铁衣 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
我最近打算把应用里面写文件的性能提升一下。
一直以来都听说NIO能提升读写文件的性能,所以做了个测试。
但测试结果却发现NIO性能还不如传统的FileWriter。

方式一(传统方式):
FileWriter fw = new FileWriter("D:\\fileTest\\test.txt");
BufferedWriter bw = new BufferedWriter(fw);
long l = System.currentTimeMillis();
StringBuffer sub = null;
for (int i = 0; i < 200000; i++) {
sub = new StringBuffer();
for (int j = 0; j < 60; j++) {
sub.append("“很好,有些见地。”");
if (j < 39) {
sub.append(",");
}
}
bw.write(sub.toString());
bw.newLine();
}
bw.close();
System.out.println("执行时间:" + (System.currentTimeMillis() - l));
-----------------------------------------------------------
执行三次:
1.执行时间:1955
2.执行时间:1938
3.执行时间:1966

可以看出基本在2秒以内

方式二(NIO 缓冲区、通道方式):
FileOutputStream fos = new FileOutputStream(new File("D:\\fileTest\\test.txt"));
FileChannel fc = fos.getChannel();
ByteBuffer bb = ByteBuffer.allocate(2048);
long l = System.currentTimeMillis();
try {
StringBuffer sub = null;
for (int i = 0; i < 200000; i++) {
sub = new StringBuffer();
for (int j = 0; j < 60; j++) {
sub.append("“很好,有些见地。”");
if (j < 39) {
sub.append(",");
}
}
bb.put(sub.toString().getBytes());
bb.put("\n".toString().getBytes());
bb.flip();
fc.write(bb);
bb.clear();
}
fc.close();
fos.close();
System.out.println("执行时间:" + (System.currentTimeMillis() - l));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != fc) {
fc.close();
}
if (null != fos) {
fos.close();
}
}
-----------------------------------------------------------
执行三次:
执行时间:3255
执行时间:3022
执行时间:2996

从上面的测试结果看出,NIO的方式每次都需要3秒左右,性能更差。
是不是我的NIO代码写的有问题,请高手帮忙分析一下。
...全文

相关推荐

评论 14
收藏 已收藏
分享
返回顶部
铁衣
Java SE 62,621 成员 307,251 内容