İsmet Alkan
İsmet Alkan

Reputation: 5447

why is BufferedImage initialized faster than Image

I'm running some tests for my project written in Java, about images. I got an interesting result and cannot figure out why. Here is the initialization lines of BufferedImage and Image.

File[] files = new File("C:\\Users\\SAMSUNG\\Desktop\\img\\").listFiles();
time = System.currentTimeMillis();
for (File f:files){
    Image img = ImageIO.read(f);
}
System.out.println((System.currentTimeMillis() - time) + " miliseconds.");

BEWARE: These two operations are run separately. I run the above one, process ends, I mean actually gets killed ends, than I run the below one.

File[] files = new File("C:\\Users\\SAMSUNG\\Desktop\\img\\").listFiles();  
time = System.currentTimeMillis();
for (File f:files){
    BufferedImage bimg = ImageIO.read(f);
}
System.out.println((System.currentTimeMillis() - time) + " miliseconds.");

I'm aware that running these in a run may affect results as I try to reach same files, for that I run them separately. The results are near 40 minutes. However, BufferedImage initialization is always a minute faster than Image initialization. Why is that?

I run the tests three times and the result is the same.

Upvotes: 2

Views: 457

Answers (2)

Jeff Watkins
Jeff Watkins

Reputation: 6357

Firstly, make sure you do more than one run of a test like that (i.e. stick the entire loop in a loop), secondly use System.NanoTime as it's WAY more accurate, thirdly as the other poster suggested, try altering the execution order or doing your runs in isolation (probably the safest way).

Upvotes: 0

iluxa
iluxa

Reputation: 6969

Times should be identical. I suspect your first loop is warming up some caches with the files' content, and the second loop has an easier time at it.

Try reversing the reading order: first BufferedImages, then Images, and check what happens

Upvotes: 7

Related Questions