简体   繁体   English

衡量Java中对象创建的性能

[英]Measuring performance of object creation in Java

I'm trying to compare performance of creation the object of some class with creation of String from byte[] . 我试图将创建某些类的对象与从byte[]创建String性能进行比较。 Here is the benchmark I wrote for this: 这是我为此编写的基准:

public class MyBenchmark {
    @Benchmark
    @BenchmarkMode(Mode.AverageTime)
    @OutputTimeUnit(TimeUnit.NANOSECONDS)
    public void tsts(Blackhole b) {
        b.consume(new TestClass(i(), str()));
    }

    @Benchmark
    @BenchmarkMode(Mode.AverageTime)
    @OutputTimeUnit(TimeUnit.NANOSECONDS)
    public void str(Blackhole b) {
        b.consume(new String(b()));
    }

    @CompilerControl(CompilerControl.Mode.DONT_INLINE)
    public String str(){
        return "asdasfa";
    }

    @CompilerControl(CompilerControl.Mode.DONT_INLINE)
    public int i(){
        return 23;
    }

    @CompilerControl(CompilerControl.Mode.DONT_INLINE)
    public byte[] b(){
        return new byte[]{49, 66, 43, 65, 78, 123, 96, 54};
    }
}

where 哪里

private static class TestClass{
    private int i;
    private String s;

    public TestClass(Integer i, String s) {
        this.i = i;
        this.s = s;
    }
}

On my machine I got the following results: 在我的机器上,我得到以下结果:

Benchmark         Mode  Cnt   Score   Error  Units
MyBenchmark.str   avgt   20  47.695 ± 1.869  ns/op
MyBenchmark.tsts  avgt   20   6.999 ± 0.191  ns/op

Is it correct way to do this? 这是正确的方法吗? Or I made some mistake in the benchmark and missed something? 还是我在基准测试中犯了一些错误并错过了一些东西?

This is because JIT knows the exact address of the literal String isntance ("asdasfa"). 这是因为JIT知道字面字符串Nottance(“ asdasfa”)的确切地址。 So in that case there is no need for creating a new object. 因此,在这种情况下,无需创建新对象。 You can clearly see it if you decompile str() method: 如果您反编译str()方法,则可以清楚地看到它:

0x000000010dd1a2b0: sub    rsp,0x18
0x000000010dd1a2b7: mov    QWORD PTR [rsp+0x10],rbp  ;
0x000000010dd1a2bc: movabs rax,0x1bc1f1440    ;   {oop("asdasfa")}
0x000000010dd1a2c6: add    rsp,0x10
0x000000010dd1a2ca: pop    rbp
0x000000010dd1a2cb: test   DWORD PTR [rip+0xfffffffffe642d2f],eax           # 0x000000010c35d000;
0x000000010dd1a2d1: ret    

The method consists of one instruction movabs rax,0x1bc1f1440 which puts an address to rax register, that's why it's a lot more faster. 该方法由一条指令movabs rax,0x1bc1f1440组成,该指令将地址放入rax寄存器,这就是为什么它要快得多的原因。 Other instructions are auxiliary. 其他说明是辅助的。

For the other method str(Blackhole b) you will see a lot more including a compiled body of String constructor with getting a default charset and decoding of byte array through method call. 对于其他方法str(Blackhole b),您将看到更多内容,包括String构造函数的编译主体,该主体具有默认字符集和通过方法调用对字节数组进行解码。

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

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