Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it faster to call a method as I initialise an object or hold it as a variable and call the method on that

Tags:

java

object

Assuming that there is a class ClassA which gives a value that I need through non-static method.

In case when I just need a value from an instance of the ClassA, I guess there are two possible choices.

double value =0 ; // The value I actually need, the object is just transitory

1) ClassA a = new ClassA (hogehoge);
   value = a.getValue();

2) value = new ClassA(hogehoge).getValue();

I know there maybe an advantage or disadvantage for both. but generally speaking what is the difference between them?

in case 2), memory use is smaller than 1) or....

like image 280
Kensuke Konishi Avatar asked Jul 02 '13 12:07

Kensuke Konishi


People also ask

Which method is called automatically when an object is initialized?

If the class has an initializer method, this method is used to get the attributes (i.e. the state) of the new object properly set up. A special method in Python (called __init__) that is invoked automatically to set a newly created object's attributes to their initial (factory-default) state.

What method is called just before an object is instantiated?

The constructor method is used to initialize data. It is run as soon as an object of a class is instantiated. Also known as the __init__ method, it will be the first definition of a class and looks like this: class Shark: def __init__(self): print("This is the constructor method.")

What happens when you call a method on an object?

Calling an object's method is similar to getting an object's variable. To call an object's method, simply append the method name to an object reference with an intervening '. ' (period), and provide any arguments to the method within enclosing parentheses.

Which method is used to initialize objects?

A constructor is used to initialize an object when it is created.


1 Answers

Actually this two piece of code will have a small difference:

***** Class1.p
       8: invokespecial #4                  // Method ClassA."<init>":(Ljava/lang/String;)V
      11: astore_3
      12: aload_3
      13: invokevirtual #5                  // Method ClassA.getValue:()D
      16: dstore_1
      17: dload_1
      18: dreturn
}
***** CLASS2.P
       8: invokespecial #4                  // Method ClassA."<init>":(Ljava/lang/String;)V
      11: invokevirtual #5                  // Method ClassA.getValue:()D
      14: dstore_1
      15: dload_1
      16: dreturn
}
*****

I.e. we see here two additional instructions for variant #1:

      11: astore_3
      12: aload_3

But it seems, that after jvm warms-up these instructions will be optimized (eliminated) and it will be no difference at all.

like image 193
Andremoniy Avatar answered Sep 19 '22 14:09

Andremoniy