3

As far as I understand the JVM, it should generally be cheaper to invoke a method (i.e. allocate a new stack frame, etc), than to create a new object.

However, can we estimate just how big the difference in overhead between the two generally is, assuming that both the method and the object declare the same number of local/instance variables of the same type, and instantiate them to the same values?

csvan
  • 8,782
  • 12
  • 48
  • 91
  • out of curiosity, why are you trying to figure this out i.e. what's the bigger objective? – Scorpion Feb 08 '13 at 11:59
  • 1
    This may help: http://stackoverflow.com/questions/320980/steps-in-the-memory-allocation-process-for-java-objects – Christophe Roussy Feb 08 '13 at 12:00
  • 1
    Just keep in mind that, whereas an object can be instantiated and passed around for as long as needed, a method and its local variables only 'exist' for as long as the method is executing. If this is an attempt at micro-optimization I would suggest studying your program flow real hard to determine where the real issues may lie. – Perception Feb 08 '13 at 12:08
  • 1
    @Scorpion - mostly, it is out of personal curiosity and desire to get a deeper understanding of how the JVM works. Practically speaking, a current project I work on requires a fair bit of traversing rather complex, recursive ADTs. Currently I use recursive methods to do so (many of them not tail recursive), and I wanted to explore if I could do a better job through visitors, for example. – csvan Feb 08 '13 at 12:15
  • 1
    your curiosity will make us all knowledgeable :-) – Scorpion Feb 08 '13 at 13:09

2 Answers2

1

In modern JVMs object creation is extremely fast operation. See this article, for example. It says: "Sun estimates allocation costs at approximately ten machine instructions".

Mikhail Vladimirov
  • 13,572
  • 1
  • 38
  • 40
0

Even though in that scenario method() needs to be scaffolded into a class ??

and registering class in JVM heap itself includes member (method()) meme allocation.

so , in any case object creation is little bit on higher side.

TheWhiteRabbit
  • 15,480
  • 4
  • 33
  • 57