Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does the creation of temporary helper variables make sense?

Tags:

java

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?

like image 941
membersound Avatar asked Dec 06 '25 08:12

membersound


1 Answers

There us no "better" approach:

  1. when you call list.size or a local size parameter it has the same performance
  2. According to Doug Lea, declaring a local parameter as final might lead to performance improvement
  3. The only aspect which is "easiness of use" is when you want a "shorter" parameter so by using: a local size parameter instead of myListOfReallyNiceIntegers.size would be easier to read/write (with for-loops etc).
like image 138
Nir Alfasi Avatar answered Dec 08 '25 21:12

Nir Alfasi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!