【问题标题】:IO and NIO performance difference and exampleIO和NIO的性能区别及例子
【发布时间】:2013-04-10 03:36:32
【问题描述】:

我对 Java NIO 很陌生,没有动手。关于 Java NIO,我知道它比 java.IO 快。

所以,为了尝试一下,我想到了编写简单的程序 “将一个文件的内容复制到另一个文件”。 "从大文件中搜索单词"。

同时使用 java.io 和 java.nio 包。

另外,我分别打印了操作开始和结束前后的时间。

我没有发现 NIO 更快的任何区别。可能是我走错了方向。

任何人都可以指导我通过示例正确看到差异的场景吗?

编辑:

得知这个问题会得到反对票,我真的很惊讶。 我已经提到我是 NIO 的新手,如果我走错了方向,我会指导我。 我没有发布程序,因为它是非常基本的读写操作...请看下面我用来测试的程序...

使用 IO

public static void copyFile(File in, File out) throws Exception {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    Date now = new Date();
    String strDate = sdf.format(now);

    System.out.println("Before Read :"+strDate);


    FileInputStream fis  = new FileInputStream(in);
    FileOutputStream fos = new FileOutputStream(out);
    try {
        byte[] buf = new byte[1024];
        int i = 0;
        while ((i = fis.read(buf)) != -1) {
            fos.write(buf, 0, i);
        }
    } 
    catch (Exception e) {
        throw e;
    }
    finally {
        if (fis != null) fis.close();
        if (fos != null) fos.close();
    }

    Date now1 = new Date();
    String strDate1 = sdf.format(now1);

    System.out.println("After Read :"+strDate1);


}

使用蔚来

 public static void copyFile(File in, File out) 
        throws IOException 
{

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    Date now = new Date();
    String strDate = sdf.format(now);

    System.out.println("Before Read :"+strDate);

    FileChannel inChannel = new
        FileInputStream(in).getChannel();
    FileChannel outChannel = new
        FileOutputStream(out).getChannel();
    try {
        inChannel.transferTo(0, inChannel.size(),
                outChannel);
    } 
    catch (IOException e) {
        throw e;
    }
    finally {
        if (inChannel != null) inChannel.close();
        if (outChannel != null) outChannel.close();
    }

    Date now1 = new Date();
    String strDate1 = sdf.format(now1);

    System.out.println("After Read :"+strDate1);
}

我从一个文件复制到另一个文件的文件大约是 20 MB。

【问题讨论】:

  • 为什么不显示用于比较的代码?也许有一个错误导致 NIO 版本变慢。
  • 您应该使用比 1024 大得多的缓冲区。如今的磁盘集群大小至少为 4096,并且您永远不应低于此值。而且您必须循环调用 transferTo() ;不能保证在一次调用中完成。

标签: java jakarta-ee io nio


【解决方案1】:

NIO 允许您仅使用单个(或更少)线程来管理多个通道,但代价是解析数据可能比使用标准 IO 从阻塞流中读取数据要复杂一些。

如果您需要同时管理数千个打开的连接,每个连接只发送少量数据,例如聊天服务器,在 NIO 中实现服务器可能是一个优势。同样,如果您需要与其他计算机保持大量开放连接,例如在 P2P 网络中,使用单个线程来管理所有出站连接可能是一个优势。

如果您的连接较少且带宽非常高,一次发送大量数据,则应该选择标准 IO 服务器实现。

参考:Difference between standard IO and NIO

【讨论】:

    【解决方案2】:

    NIO 更快并不是真的。保罗·泰玛(Paul Tyma)在过去的某个时候打破了这个神话。

    http://mailinator.blogspot.in/2008/02/kill-myth-please-nio-is-not-faster-than.html

    http://paultyma.blogspot.in/2008/03/writing-java-multithreaded-servers.html

    【讨论】:

      猜你喜欢
      • 2014-08-20
      • 2015-02-16
      • 1970-01-01
      • 2011-02-03
      • 1970-01-01
      • 1970-01-01
      • 2013-02-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多