I use to the advice given by Joshua Bloch's Effective Java, Item 52: Refer to objects by their interfaces
.
However, in most of the sample code comes with Android, I realize the following code is quite common.
private ArrayList<Integer> mPhotos = new ArrayList<Integer>();
I understand this is due to performance optimization purpose, as the following code will be slower.
private List<Integer> mPhotos = new ArrayList<Integer>();
However, is such optimization technique still valid? As if I read from http://developer.android.com/guide/practices/design/performance.html
On devices without a JIT, it is true that invoking methods via a variable with an exact type rather than an interface is slightly more efficient. (So, for example, it was cheaper to invoke methods on a HashMap map than a Map map, even though in both cases the map was a HashMap.) It was not the case that this was 2x slower; the actual difference was more like 6% slower. Furthermore, the JIT makes the two effectively indistinguishable.
Do we need to assume our devices are without JIT, and refer objects without interfaces? Or, shall we just adopt to Joshua Bloch's advice?
As of Android 2.2, the Dalvik VM (that runs the Dalvik bytecode that is the result of your Java source code) has a Just-in-time compiler (JIT).
I don't know if this particular optimization is part of the JIT or not, but it should be testable on actual devices.
If you target pre-2.2 devices and those 6% overhead in invocation (which is not to be confused with an overal 6% slowdown of your application!) has a serious effect on your application, then that optimization might be worthwhile.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With