Calling the getter method again in for-loop

Which cycle is faster, does it even matter?

final int cSize = getSize();
for(lineCount = 0; lineCount <= cSize; lineCount++) {
   // Do something!
}

or

for(lineCount = 0; linecount <= getSize(); lineCount++) {
   // Do something!
}

Where getSize()is a simple getter:

private int getSize() {
   return this.size;
}
+4
source share
2 answers

Assuming it is this.sizenot final, the two loops have different semantics:

  • The first cycle will not respond to changes sizemade within the cycle; it will be executed as many times as the variable requires cSize.
  • The second cycle will respond to changes size. If sizeincreasing or decreasing, also the number of iterations of the loop.

, Java- " " , this.size, . .

+2

:

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class ForLoopPerformanceTest {
private static List<Integer> list = new ArrayList<>();
private static long startTime;
private static long endTime;

static {
    for (int i = 0; i < 1_00_00_000; i++) {
        list.add(i);
    }
}

@SuppressWarnings("unused")
public static void main(String[] args) {
    // Type 1
    startTime = Calendar.getInstance().getTimeInMillis();
    for (Integer i : list) {
        //
    }
    endTime = Calendar.getInstance().getTimeInMillis();
    System.out.println("For each loop :: " + (endTime - startTime) + " ms");

    // Type 2
    startTime = Calendar.getInstance().getTimeInMillis();
    for (int j = 0; j < list.size(); j++) {
        //
    }
    endTime = Calendar.getInstance().getTimeInMillis();
    System.out.println("Using collection.size() :: " + (endTime - startTime) + " ms");

    // Type 3
    startTime = Calendar.getInstance().getTimeInMillis();
    int size = list.size();
    for (int j = 0; j < size; j++) {
        // System.out.println(j);
    }
    endTime = Calendar.getInstance().getTimeInMillis();
    System.out.println(
            "Using [int size = list.size(); int j = 0; j < size ; j++] :: " + (endTime - startTime) + " ms");

    // Type 4
    startTime = Calendar.getInstance().getTimeInMillis();
    for (int j = list.size(); j > size; j--) {
        // System.out.println(j);
    }
    endTime = Calendar.getInstance().getTimeInMillis();
    System.out.println("Using [int j = list.size(); j > size ; j--] :: " + (endTime - startTime) + " ms");
}
}

:: 108 ms

collection.size():: 39 ms

[int size = list.size(); int j = 0; j < ; j ++]:: 4 ms

[int j = list.size(); j > ; j--]:: 0 ms

-3

Source: https://habr.com/ru/post/1616899/


All Articles