Search code examples
androidvariablesandroid-contextgetstring

What's better in a loop - context.getString() or a variable?


I use some strings which are defined in a resource file. What is better in terms of resource usage and performance? Call context.getString(stringId) every single loop or store the context.getString(stringId) in a variable outside of the loop and use this variable within the loop.

Some pseudocode ...

Without a variable:

while (condition) {
   DoSomethingWithString(context.getString(stringId));
}

With a variable:

String variable = context.getString(stringId);
while (condition) {
   DoSomethingWithString(variable);
}

Some more thoughts ... the variable stuff looks like to be the better solution because there is no need to fetch the data from the resource file every time. But you have to use one more variable. OK, it's just one variable in this case but it's also only a pseudo example so it could maybe add some resource usage. Beside this the resourcestring have to copied to another string before this string is used (performance?). The usage of context.getString(stringId) within a loop could be the better solution when the bytecode compiler does a good optimizing job.


Solution

  • (As per my understanding of your question) I advise you to store the context.getString(stringId) in a variable outside of the loop and use this variable within the loop.

    Because, In this, in for loop your program executer doesn't need to go every time to fetch data from String file. It just refer the single variable.

    For example:

    String result = context.getString(id);
    
    for(int i=o;i<some.size();i++)
    {
     Log.d(TAG, result);
    }