本文起因是團隊在確定 Android 實體類變量的訪問修飾符(private | public)時,存在不同的建議。
原因如下文,結果在最后:
WHY YOU SHOULDN’T USE GETTERS AND SETTERS ON ANDROID
也就是在 Android 手機中,調用 getter/setter 方法會比直接訪問變量耗費更多的性能。
而在 Android Developers 的 Performance Tips 中是這么說的:
Avoid Internal Getters/Setters
However, this is a bad idea on Android. Virtual method calls are expensive, much more so than instance field lookups. It’s reasonable to follow common object-oriented programming practices and have getters and setters in the public interface, but within a class you should always access fields directly.
Note that if you’re using ProGuard, you can have the best of both worlds because ProGuard can inline accessors for you.
Google 的意思呢就是,對外提供 getter/setter,對內直接訪問。使用 proguard 可以兼具性能和規范。
三星SM-G9006W 高通 驍龍801,2.5GHz,2GB
使用原文中的 DeltaExample 進行測試,部分代碼如下:
Low-end device (Samsung i5500):
High-end device (LG Nexus 4):
測試結果如下圖,可直接看最后一項,Task 平均執行時間
直接訪問變量:
開啟混淆:
發現并沒有性能提升,原因是較新的 Android SDK 默認關閉了優化:
Android Proguard does not inline
與混淆前速度相同
optimize 之后,速度與 public 直接訪問變量一致
與混淆前和直接混淆速度相同,此處就不多放圖片了
原文轉自: http://blog.qiji.tech/archives/14577