While I know setting typeface on a TextView is not a big deal but setting it in a wrong can effect the performance of your app badly. First
approach that is being used by many developers is calling setTypeface on TextView when it is created e.g.
While this is a nice approach if you only need to set typeface on a single TextView which is rare.
If you need to use the same view throughout the app, a nice approach would be to extend the TextView and set the typeface there. With this
approach you get maximum flexibility - you can change or update font any time without going through the hassle of setting it individually
on every view throughout the app.
While setting typeface by extending TextView gives us flexibility but performace wise it is same as setting it on individual text views i.e.
setTypeface is called for every TextViewand typeface is created from assets for every TextView. With this you can guess that
createFromAsset is called from every view.
If you a few custom typefaced views in your layout, performance is negligible but as soon as the number of views grow, performance becomes an
issue. The method which creates typeface from assets is time expensive. To clear my doubt, I tried to log the time of creating typeface
I have three robot fonts (bold, light, regular) in my assets directory and I use all three in my layouts. Here is the time createFromAssets
takes to load font from assets.
5 ms is not bad if there is only one view otherwise time will increase linearly with views - more typefaced views, more time.
A better approach
To avoid creating typefaces every time, a better approach would be to create a singleton typeface helper which caches the generated typefaces and
pass it to views whenever needed.
Here is a simple helper class.
In order to test it, create three custom TextViews and use them in a simple layout. In my layout, I have used them 28 times
just to compare performance better (with more time, it is easy to compare).
BoldTextView (uses roboto bold font)
LightTextView (uses roboto light font)
RegularTextView (uses roboto regular font)
All text views are same (with different font) as BoldTextView in the above example.
Without caching fonts
Starting the activity 15 times without caching the fonts results in average start time of +232.6ms.
With caching fonts
Starting the activity 15 times with caching the fonts results in average start time of +116.2ms.
100% performance is gained from non-cached 232ms start time to cached 116ms start time.
Regardless of these approximate results, you always get performance gain when fonts are cached.
Please note that these results are not 100% correct i.e. you don’t always get a 100% performance gain. These results are approximate,
calculated just to show there is a performance gain.
Source code for this article is available on github .