Reputation: 779
Is there any difference in efficiency between the 2 code snippets below? Does the first one require it to allocate memory for the object?
Class c = a.getClass();
if(str != null)
c.dosomething(c.getX())
if(a.getClass() != null)
a.getClass().doSomething(a.getClass().getX());
Upvotes: 1
Views: 79
Reputation: 718798
The chances are that the 1st form will be more efficient. (And it is hard to imagine how it would be less efficient if the code is JIT compiled.)
If the JIT compiler can prove to itself that the 2nd and subsequent calls to getClass()
are side-effect free and produce the same result, then it could reuse the value returned by the 1st call. That would make the 2nd form perform as fast as the 1st form.
Whether the JIT actually does / can do this optimization will be JVM dependent. My gut feeling is that current generation JITs probably don't do it, but I could be wrong. You would need to dump the JIT compiled native code to be sure.
It is worth noting that that:
The getClass() call (assuming that it is not overridden) is going to be relatively cheap. All it does is lookup an existing Class
object that corresponds to something in the object's header. (And we know it doesn't create a new Class
object each time because the Java specs say that there is a 1-to-1 relationship between Class
objects and Java types ...)
Unless this code is a performance bottleneck, it won't make a significant difference to the application's overall speed which way you implement this. (Beware of premature optimization ...)
Upvotes: 0
Reputation: 5537
Which is more efficient really depends on what the JIT compiler and the JVM do when you run the code. Since these are platform and implementation dependent, it's hard to give a definite answer.
Whatever memory allocated for the Class object c should be allocated in the getClass()
method. c in your function is just a reference and is most likely stored inside a register so memory allocation will be needed. Function calls are relatively expensive compared to storing data inside a register. I doubt JIT will be smart enough to refactor the bytecode for your second snippet into the first snippet though, so the first method will most likely be faster.
However, for the sake of code style, you should always go with the first method.
Upvotes: 1
Reputation: 256
First one will be much more efficient, especially if the getObject method is expensive. If any memory is allocated for c, this is done inside the getObject method.
Upvotes: 1