I was going through some code today and saw this:
x.add(getResources().getString(R.string.none));
x.add(getResources().getString(R.string.today));
x.add(getResources().getString(R.string.tomorrow));
...
and so I thought, “that’s inefficient!” and started to change it to:
Resources res = getResources();
x.add(res.getString(R.string.none));
x.add(res.getString(R.string.today));
x.add(res.getString(R.string.tomorrow));
...
but then I stopped and wondered: Is the second section of code really more efficient or does it not really matter? Is the compiler going to generate the same byte code either way?
The compiler will not generate the same byte code, but if
getResources()is a trivial method then the JIT-compiler may effectively run the same code at execution time.Personally I prefer the second form on the grounds of it being cleaner and more readable rather than for performance reasons.