繁体   English   中英

RandomAccessFile writeInt(int i)vs write(byte [] b)-性能

[英]RandomAccessFile writeInt(int i) vs write(byte[] b) - performance

今天,我对RandomAccessFile遇到了一件有趣的事情。

我注意到,使用RandomAccessFilewriteInt(int i)方法要比使用RandomAccessFilewrite(byte[] b)慢得多,在这里我首先将int值转换为byte [4]数组。

我正在使用此代码进行转换

private static byte[] intToByte(int i)
{
   byte[] result = new byte[4];

   result[0] = (byte) (i >> 24);
   result[1] = (byte) (i >> 16);
   result[2] = (byte) (i >> 8);
   result[3] = (byte) (i);

  return result;
}

区别非常明显,有利于write(byte[] b)

使用JDK 8在笔记本电脑上写一百万个int

  • 通过writeInt(int i)方法花费了大约9秒钟
  • 通过write(byte[] b)花费了大约2.3秒

在另一个使用JDK 7和完全不同的机器的环境中,我得到了类似的结果。

writeInt(int i)方法委托给本机write0(int b)方法,而write(byte[] b)委托给本机writeBytes

当我进行性能分析时,我注意到使用它时,大部分执行时间都花在了writeInt方法上。

有谁知道我为什么看到如此大的差异? 似乎writeInt效率较低。

RandomAccessFile实际上有两个本地方法来写入字节:

//writes an array
private native void writeBytes(byte b[], int off, int len) throws IOException;

//writes one byte
public native void write(int b) throws IOException;

方法writeInt(int)使用本机write(int)方法分别写入每个字节,而write(byte [])使用本机writeBytes(byte [],int,int)方法。

writeInt方法执行4种方法调用来写入传递的整数值的每个字节,另一种方法仅使用一个调用来写入数组。 方法调用实际上是java中昂贵的操作:对于每次调用,JVM都会为操作数堆栈和局部变量数组分配额外的内存。

我不打算详细介绍我所做的更改,但是您的测试有些缺陷。 我自由地进行了一些更新,并且也进行了一些测试:

@BenchmarkMode(value = { Mode.AverageTime })
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Warmup(iterations = 2, time = 2, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 2, time = 2, timeUnit = TimeUnit.SECONDS)
public class RandomAccessWriteFileTest {

    public static void main(String[] args) throws Exception {
        Options opt = new OptionsBuilder().include(RandomAccessWriteFileTest.class.getSimpleName())
                .jvmArgs("-ea")
                .shouldFailOnError(true)
                .build();
        new Runner(opt).run();
    }

    @Benchmark()
    @Fork(1)
    public long benchamrkWriteDirectInt(BenchmarkPlainIntSetup setupTest) {
        try {
            setupTest.raf.writeInt(6969);
            return setupTest.raf.length();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Benchmark()
    @Fork(1)
    public long benchamrkWriteConvertedInt(BenchmarkConvertedIntSetup setupTest) {
        try {
            setupTest.raf.write(intToBytes(6969));
            return setupTest.raf.length();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static byte[] intToBytes(int i) {
        byte[] result = new byte[4];

        result[0] = (byte) (i >> 24);
        result[1] = (byte) (i >> 16);
        result[2] = (byte) (i >> 8);
        result[3] = (byte) i;

        return result;
    }

    @State(Scope.Thread)
    static public class BenchmarkConvertedIntSetup {

        public RandomAccessFile raf;

        public File f;

        @Setup(Level.Iteration)
        public void setUp() {
            try {
                f = new File("jmhDirectIntBenchamrk.ser" + ThreadLocalRandom.current().nextInt());
                raf = new RandomAccessFile(f, "rw");
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            }
        }

        @TearDown(Level.Iteration)
        public void tearDown() {
            f.delete();
        }
    }

    @State(Scope.Thread)
    static public class BenchmarkPlainIntSetup {

        public RandomAccessFile raf;

        public File f;

        @Setup(Level.Iteration)
        public void setUp() {
            try {
                f = new File("jmhDirectIntBenchamrk.ser" + ThreadLocalRandom.current().nextInt());
                raf = new RandomAccessFile(f, "rw");
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            }
        }

        @TearDown(Level.Iteration)
        public void tearDown() {
            f.delete();
        }
    }
}

绝对会有结果差异(每个操作的毫秒数)

 benchamrkWriteConvertedInt  0.008 
 benchamrkWriteDirectInt     0.026

不知道为什么(可能会在以后的一段时间中挖掘程序集来理解,但是我可以确认您的发现。很好的问题!)

这是使用最新的Java-8和Java-9 btw运行的

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM