I'd like to know in which cases you would prefer to create some kind of "helper" variable to access a value that might be used 2 or more times in a method.
I came around this question during following snipped: what is better: two times accessing the size
value of a List
, or creating an Integer
variable that holds the size of the list?
List<String> list;
private myIndexHelper() {
if (list.size % 2 == 0) {
return PREFIX + list.size;
}
return "";
}
private myIndexHelper() {
int size = list.size;
if (size % 2 == 0) {
return PREFIX + size;
}
return "";
}
I know this might probably be over-optimization. But also in general (neglecting performance): would you rather access the list.size property numerus times, or create a variable that hold the size?