Asset Reduction
Let’s say that we are working on application that uses a lot of similar Drawables. In this example we are trying to display 20 images.
Each image has different color.
Loading Drawable
Loading Drawable is simple as ContextCompat.getDrawable(this, drawableRes)
Inside this method some things happends that might interest you:
- Bitmap reading and decoding occurs so it is quite expensive for CPU
- once Drawable is loaded it is cached in internal android DrawableCache. Second call to getDrawable is much faster
Nevertheless we need to load 20 unique Drawables – what technique should be used to optimize this?
Asset Reduction
Asset Reduction is a technique of reducing assets in order to modify existing one at runtime. Let’s apply it to our example.
Instead of having 20 different Drawables in every color – we leave only one and then color for each is applied at runtime using code below
Notice that we have to call mutate() to make sure that setColorFilter is not shared between other Drawable.
A little more from documentation
Make this drawable mutable. This operation cannot be reversed. A mutable drawable is guaranteed to not share its state with any other drawable. This is especially useful when you need to modify properties of drawables loaded from resources. By default, all drawables instances loaded from the same resource share a common state; if you modify the state of one instance, all the other instances will receive the same modification. Calling this method on a mutable Drawable will have no effect.
Result
As a result app is 300 KB lighter and loading images takes ~15 times faster than using 20 different Drawables.