Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the first call to constructor takes 10 times more time than other ones?

class testx
{
  public testx()
  {
    long startTime = System.nanoTime();
    System.out.println((System.nanoTime() - startTime));
  }

  public static void main(String args[])
  {
      new testx();
      new testx();
      new testx();
  }
}

I always get results similar to this 7806 660 517. Why the first call takes 10 times more time than other ones?

like image 533
good_evening Avatar asked Aug 17 '12 19:08

good_evening


People also ask

Can we call constructor more than one time?

Constructors are called only once at the time of the creation of the object.

Why this () expression should always be the first line of the constructor?

It is just stopping you from executing logic that you can't fit into a single expression. There are similar rules for calling this() . The compiler says, call to this must be first statement in constructor .

Why constructor is called first?

This is why the constructor of base class is called first to initialize all the inherited members.

How many times can the constructor be invoked?

Constructor is called about 3 times. Deconstructor is also called about 2 times. Some times in an unexpected order like Costructor, Constructor, Deconstructor, Constructor, Deconstructor.


1 Answers

Because the JVM loads a bunch o' classes for the first time at that point. Once that first System.nanoTime() returns, you have already loaded System.class and testx.class, but once System.out.println comes into the picture, I suspect a lot of I/O classes get loaded up, and that takes some time.

In any event, this is not a good benchmarking technique; you should really be warming up the JIT by running something for ~10000 iterations before you start measuring it. Alternately (and preferably), use a pre-built benchmarking tool like Caliper.

like image 110
Louis Wasserman Avatar answered Oct 21 '22 23:10

Louis Wasserman