为啥我这测试nio比不用还慢啊

来源:2-10 Buffer的原理和使用场景-面试题解读(2)

慕沐4323715

2021-08-07

bio的 10毫秒

    @Test
    public  void read_buffer() throws IOException {
        String fileName = "word";

        BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(fileName));

        long start = System.currentTimeMillis();

        int b;
        byte[] bytes = new byte[1024];
        while ((b = inputStream.read(bytes)) != -1){

        }
        inputStream.close();

        System.out.println(System.currentTimeMillis() -start);
    }

nio的 30毫秒

    @Test
    public  void read_test_nio() throws IOException {
        String fileName = "word";
        FileChannel channel = new FileInputStream(fileName).getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        long start = System.currentTimeMillis();

        while (channel.read(buffer) != -1){
            // 翻转 进行读
            buffer.flip();
            // 清空 继续写
            buffer.clear();
        }

        channel.close();

        System.out.println(System.currentTimeMillis() - start);
    }
写回答

1回答

求老仙

2021-08-09

nio也不过是帮你最好了缓冲。buffer设置成,4k,8k试试

0
0

笑傲Java面试 剖析大厂高频面试真题 秒变offer收割机

深度剖析大厂面试高频真题,让你秒变offer收割机

1783 学习 · 314 问题

查看课程