Better to load resources on the run or to pre load

2019-09-17 21:02发布

问题:

I'm developing an app that spans across several classes, and as such, I've had to pass on the app's Context to all of the classes that use global strings or integers so as to extract them from the strings.xml or dimens.xml files instead of hard coding them. Up until now I've been loading the resources once needed but I was wondering if it would be more efficient to load all the resources I would need on a class in the Constructor, keep in mind that they're only strings and integer values.

回答1:

For small Objects (Strings, Numbers) you can preload them as it wouldn't take much memory.

For big Objects (Images,Media) it is better to load as needed.

My personal preference for small Objects is to lazy load them (load as needed but after loading keep in memory for later use), something like:

public class Values{
     private static Object pref1;

    public static Object getPreference1(){
         if(pref1 == null){
             pref1 = heavyLoadingOfPref1();
         }
         return pref1;
    }
} 

As, noticed I use it for sorts of small objects, for Strings (especially local Resources) it is more of a bother to load them like this, just load them once at begining (if you have defined them then it is more likely they will be used).