Search code examples
androidfontsassetsandroid-context

Passing Context unnecessarily. Is it costly?


So, I have this method getSpecialCharacter that's called from many different activities.

public static Spanned getSpecialCharacter(Context context){
    Spanned spanned_character = CacheFactory.spannedCache.get("green");
    if (spanned_character ==null) {
        spanned_character = getSymbolColor(context, " \uf100", Color.GREEN);
        CacheFactory.spannedCache.put("green", spanned_character);
    }
    return spanned_character;
}

private static Spanned getSymbolColor(Context context, String s_symbol, int color){
    Typeface font = Typeface.createFromAsset(context.getAssets(), "font.ttf");
    SpannableString ss = new SpannableString(s_symbol);
    ss.setSpan (new CustomTypefaceSpan(font), 0, s_symbol.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    ss.setSpan(new ForegroundColorSpan(color), 0, s_symbol.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return ss;
}

It basically sets a special character from a loaded font and applies the color green. It works fine. This method gets called hundreds of times, so I cache the "special character" so that the font and the span is only called once (the first time).

I have to pass the context in order to load the font, however the context is only needed the first time. I wonder if I am losing some performance by passing Context hundreds of times unnecessarily. Does this cost any performance? Any suggestions to improve my code?


Solution

  • It shouldn't. You're only actually using the passed Context if the Spanned doesn't already exist. The real performance issue would be in creating the Typeface itself, which is done only once.

    Since you're caching the Spanned and not the Context parameter, you shouldn't have a problem.


    Edit:

    If you really want to be safe about it, pass context.getApplicationContext() when calling the method. That Context never "expires" as long as your app is running, and will be GCed as soon as it stops running.