starkej2 starkej2 - 1 month ago 23
Java Question

Cost of invoking a method on Android

I created a method that's only called in one place - from

onBindViewHolder()
in a RecyclerView. It was a logical unit of code, and I think that extracting that code block into a method improved readability. However, during a code review, I was advised that the method invocation was expensive, so it would negatively impact performance, and that I should inline the code rather than putting it in a separate method.

I thought the JVM or compiler would optimize this code by inlining the method, but I'm not sure if that's the case on Android. I haven't really been able to find any concrete information about what kind of optimizations the new ART JVM does.

Is invoking a method so expensive on Android that I should avoid it at the cost of readability in places where the method might get called many times? Also, is creating single-use methods like this frowned upon because of the DEX method limit? (this app is already using multidex).

This question is not a duplicate of other similar java questions, because I'm asking specifically about the performance on Android, which has it's own idiosyncrasies.

Answer

I totally disagree. In theory, method calls do add a bit of overhead. Things have to be pushed onto the stack and then a jump to the method. But the overhead is trivial.

Premature optimization is never a good idea. Benchmark your application and figure out where the real performance issues are. I'm positive that it won't be because of a single method call, even one that is called frequently. How that method is implemented might be an issue but not the call itself.