Map generation performance improves with every new map

I have a tiled map generator which generates a 41x41 dungeon map with caves, corridors, doors and rooms. I added a timer to see how long it took which looked like:


double start;
do{
    start = System.nanoTime();

    // Map generation code here

    System.out.println("Map generated in " + ((System.nanoTime() - start) / 1000000) + "ms");
}while(!ValidMap());

Also I made the space bar generate a new map for debugging. Here’s an example console log after generating the map a few times:

[quote]Map generated in 53.11551ms
Map generated in 20.609848ms
Map generated in 9.712823ms
Map not valid, not enough valid tiles. (19.452705%)
Map generated in 7.532394ms
Map generated in 6.474681ms
Map not valid, not enough valid tiles. (31.290897%)
Map generated in 7.520545ms
Map generated in 6.564025ms
Map not valid, not enough valid tiles. (34.324806%)
Map generated in 7.090159ms
Map generated in 6.431771ms
Map generated in 5.260059ms
Map generated in 4.560361ms
Map generated in 4.998753ms
Map generated in 3.736096ms
Map not valid, not enough valid tiles. (30.041641%)
Map generated in 3.703112ms
Map generated in 3.57406ms
Map not valid, not enough valid tiles. (34.503273%)
Map generated in 14.549861ms
Map generated in 3.725848ms
Map generated in 3.484076ms
Map generated in 3.808787ms
[/quote]
I noticed that the time taken to generate each map reduced each time (with the occasion spike to 14ms).

Here’s a gif showing it in action.

Any idea why the first few generations take between 10-50ms and the rest take < 10ms?

Hello. I can not see your full code, but I think that it is normal. It needs to run up and the 1st time it needs time for loading up things, that loads only once and creating the display. The preformance can improve too because of mabye some objects are already rendered to the same position. But it is only my oppinion.

Definitely Just-In-Time compilation kicking in and transforming the code from templated interpretation to optimized compiled code. And the spikes are likely due to Garbage Collection pausing the application.

Ahh I see. So it might even be worth running the map generation a few times in the background, before the user generates a map, to improve performance slightly.