Carl Rice

View Original

Android's 64K Reference Limit

While many downplay the impact of breaking the 65,536 method reference barrier, I've come to give it a second look. "Just focus on shipping" is a saying all to rampant in tech. You often end up with throwaway solutions that really aren't focused on sustainability. There are few reasons I don't believe in Multidex even though I have to deal with it day to day.

  1. It slows down your build process. Not only is it using ProGuard every time you build, you have to bundle up that much more code. You can target API 21+ to bypass the ProGuard part, but you might need to target API 23+ pulling you further away from many of your users.
  2. It could slow down app start up. From personal experience and reported by others, your app could start between 15%-20% slower.
  3. It might be pointing to a larger problem.

At a bare minimum, you need to measure and track your method reference count. The good news is for most apps this is completely avoidable with a few key principals.  

  1. Don't pull in an entire library for a few classes and don't wait for ProGuard to strip out unused stuff for you. Consider grabbing the source directly or using Jar Jar to repackage the dependency.
  2. Avoid as much of Google Play Services, Support Library, and AppCompat as you can. While they provide a ton of handy stuff, you most likely won't use it all. Following Material guidelines is easy, enabling you to quickly build most components in fraction of the method count. With v25 you may be able to take bits and pieces of these libraries, but many still depend on each other.
  3. Be cautious of or avoid auto generated code. If you can't, find or make a better generator. Thrift is a great example where it includes a ton of extra methods many won't use. Also get your definitions in check to make sure Android only gets the enums it needs and not all the junk your server uses too.
  4. All too often people's first step is to search Android Arsenal or Github for a canned solution – write more of your own solutions! They'll be tailored to your app and often slimmer than a general purpose counterpart.
  5. Use ProGuard to remove unused methods. You are probably already doing this, but you may be able to tighten up the rules.
  6. Understand what happens when you (don't) access a private field from an inner class. There could be 1,000s of hidden methods you didn't write!
  7. Lastly, don't wait until you hit 64k methods. Continually check this and other key metrics like bundle size. This is even more important the larger your team gets.