下面两个从文件读取.class文件哪个性能更好一些?

  • fragment 1
private byte[] loadClassFromFile(String filename) {
        byte[] buffer = new byte[1024];
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        int len = 0;
        try (InputStream inputStream = getClass().getClassLoader()
                .getResourceAsStream(filename.replace('.', File.separatorChar) + ".class")) {
            if (null == inputStream) {
                return byteArrayOutputStream.toByteArray();
            }
            while ((len = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(Arrays.copyOf(buffer, len));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return byteArrayOutputStream.toByteArray();
    }
  • fragment 2
private byte[] loadClassFromFile(String fileName)  {
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream(
                fileName.replace('.', File.separatorChar) + ".class");
        byte[] buffer;
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        int nextValue = 0;
        try {
            while ( (nextValue = inputStream.read()) != -1 ) {
                byteStream.write(nextValue);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        buffer = byteStream.toByteArray();
        return buffer;
    }
阅读 1.3k
1 个回答

结论:第一个会更快

buffer是一个大小为1024的字节数组,也就是1KB,所以inputStream.read(buffer)一次可以从流中读取1KB的数据,并将读取的数据放入到byteArrayOutputStream。而inputStream.read()一次只读取一个字节,每次一读完就要放到byteArrayOutputStream,效率会比较低,而且每次write时,byteArrayOutputStream还有额外的判断动作,需要判断内部的字节数组是否足够存放,如果不够,需要将内部字节数组的大小变为原来的两倍。源码如下

public synchronized void write(int b) {
        ensureCapacity(count + 1);
        buf[count] = (byte) b;
        count += 1;
    }

private void ensureCapacity(int minCapacity) {
        // overflow-conscious code
        if (minCapacity - buf.length > 0)
            grow(minCapacity);
    }

private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = buf.length;
        // 大小变为原来的两倍
        int newCapacity = oldCapacity << 1;
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        buf = Arrays.copyOf(buf, newCapacity);
    }
推荐问题
宣传栏