How many cpu cycles an object creation takes in ja

2019-04-17 08:29发布

I am curious how many cpu cycle or time does it takes to create an object of class that has no field in java? I was disscussing it with colleague whether it would be good idea to create new object for unique way to reffer something or create uuid, in his defence he said that creating object is very light weight in java these days, which I also agree.

But question is how can it compare to something completely different like uuid generation?

Hence, the doubt how much cpu cycles does it takes to allocate object & what are exact steps involved?

1条回答
别忘想泡老子
2楼-- · 2019-04-17 09:07

Object creation in Java may take anywhere from zero to billions cycles.

  • Zero: when an object does not escape a local scope, JIT compiler may replace an allocation with local variables as a result of the allocation elimination optimization.
  • Billions, because any allocation may trigger (potentially long) garbage collection.

I've already given a high-level overview of allocation in HotSpot JVM in this and this answer.

The most common way to allocate an object in TLAB involves the following steps:

  1. Load tlab_top pointer (there is typically a dedicated CPU register for thread locals on x64).
  2. Increment it by the size of an object.
  3. Compare tlab_top + object_size against tlab_end. Jump to the slow path if needed.
  4. Store the new value of tlab_top. The previous value is the address of newly created object.
  5. Set the default header of the object.
  6. Set the klass field - the pointer to object's class metadata.
  7. Initialize the rest object data with zeros. Even an object without fields may have an alignment padding.

These all is about 10-15 CPU instructions.

Let's measure the average time of an object creation with JMH benchmark.

package bench;

import org.openjdk.jmh.annotations.Benchmark;

public class Alloc {

    @Benchmark
    public Object baseline() {
        return "Some preallocated object";
    }

    @Benchmark
    public Object newObject() {
        return new Object();
    }
}

Results:

Benchmark        Mode  Cnt  Score   Error  Units
Alloc.baseline   avgt   10  3,428 ± 0,089  ns/op
Alloc.newObject  avgt   10  4,505 ± 0,056  ns/op

So, the object allocation along with benchmarking overhead takes ~4.5 ns or around 11 cycles on a 2.4GHz CPU. That's indeed cheap comparing to UUID generation algorithms.

查看更多
登录 后发表回答