I am currently trying to improve the performance of a Java code. After digging a bit to see where optimization was required I ended up with the following setup (simplified for clarity).
The Board constructor which is called a large number of times (~200k to 2M):
public Board(Board board) {
long now = System.currentTimeMillis();
this.macroBoard = new int[9];
int [] boardToCopy = board.getMacroBoard();
for (int i = 0; i < 9; i++){
this.macroBoard[i] = boardToCopy[i];
}
long duration = System.currentTimeMillis() - now;
if (duration > THRESHOLD){
System.err.println(duration);
}
}
And in another class:
long end = System.currentTimeMillis() + SIMULATION_DURATION;
while (System.currentTimeMillis() < end) {
...
...
Board board = new Board(otherBoard);
...
...
}
The results puzzled me. In fact I observed two things:
- The larger SIMULATION_DURATION, the larger max(duration);
- The value of max(duration) can reach 2s (yes seconds, no typo) when SIMULATION_DURATION = 10s. If SIMULATION_DURATION = 100ms, I observe a max(duration) of around 30ms.
My questions are the following:
- How can the copy of a 9 integers array take so long?
- Why is duration less than 0.1ms 99% of the time and really high the remaining 1%?
- Why does it depend on the value of SIMULATION_DURATION?
- Am I making a mistake using System.currentTimeMillis() for this kind of benchmark and the results is therefore totally inaccurate?
- Is the GC involved in this strange behavior as I am creating a large number of Board objects?