Thought I’d try it also.
OS: Windows Vista
JAVA: jdk1.6
Testcase: loading 128x128 32 bit png 1k times.
(toolkit testcase also uses mediatracker and converts Image to a BufferedImage to make it a bit more fair ;))
Results:
Toolkit: 3631 ms
ImageIO: 6503 ms
And here’s my code for the test:
package star.client;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.DataInputStream;
import java.io.IOException;
/**
* User: tarmo
* Date: 25.05.2007
* Time: 21:28:19
*/
public class ImageLoadingTest {
private static final String IMAGE = "/fonts/LucidaConsole12.png";
private ImageLoader loader;
private String name;
private interface ImageLoader {
BufferedImage load(String name) throws IOException, InterruptedException;
}
public ImageLoadingTest(String name, ImageLoader loader) {
this.loader = loader;
this.name = name;
}
private void start() throws IOException, InterruptedException {
long start = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
foo(loader.load(IMAGE));
}
System.out.println(String.format(
"%s: %s", name, System.currentTimeMillis() - start));
}
public void foo(Image image) {
}
public static void main(String[] args) throws IOException, InterruptedException {
final MediaTracker tracker = new MediaTracker(new JPanel());
ImageLoadingTest test1 = new ImageLoadingTest("ImageIO", new ImageLoader() {
public BufferedImage load(String name) throws IOException {
return ImageIO.read(Main.class.getResource(name));
}
});
ImageLoadingTest test2 = new ImageLoadingTest("Toolkit", new ImageLoader() {
public BufferedImage load(String name) throws IOException, InterruptedException {
DataInputStream datainputstream = new DataInputStream(
Main.class.getResourceAsStream(name));
byte bytes[] = new byte[datainputstream.available()];
datainputstream.readFully(bytes);
datainputstream.close();
Image image = Toolkit.getDefaultToolkit().createImage(bytes);
tracker.addImage(image, 1);
tracker.waitForID(1);
tracker.removeImage(image);
BufferedImage buffered = new BufferedImage(
image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
buffered.getGraphics().drawImage(image, 0, 0, null);
return buffered;
}
});
if (args.length != 1) {
System.out.println("Usage: ImageLoadingTest <imageio|toolkit>");
System.exit(1);
}
if (args[0].equalsIgnoreCase("imageio")) {
test1.start();
} else if (args[0].equalsIgnoreCase("toolkit")) {
test2.start();
} else {
System.out.println("Invalid test.");
}
}
}