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?
Object creation in Java may take anywhere from zero to billions cycles.
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:
tlab_top
pointer (there is typically a dedicated CPU register for thread locals on x64).tlab_top + object_size
againsttlab_end
. Jump to the slow path if needed.tlab_top
. The previous value is the address of newly created object.klass
field - the pointer to object's class metadata.These all is about 10-15 CPU instructions.
Let's measure the average time of an object creation with JMH benchmark.
Results:
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.