Bartosz Sosnowski
Bartosz Sosnowski

Reputation: 3

Java JPEG compression time

I have a method that compress image to jpg format and returns an byte array of it. Here is a code of it:

public static byte[] CompressToJpeg(BufferedImage image, float compressionQuality) throws IOException {
    File compressedImageFile = new File("compressed_image.jpg");
    OutputStream os = new FileOutputStream(compressedImageFile);

    Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
    ImageWriter writer = (ImageWriter) writers.next();

    ImageOutputStream ios = ImageIO.createImageOutputStream(os);
    writer.setOutput(ios);

    ImageWriteParam param = writer.getDefaultWriteParam();

    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    param.setCompressionQuality(compressionQuality);
    writer.write(null, new IIOImage(image, null, null), param);

    os.close();
    ios.close();
    writer.dispose();

    return Files.readAllBytes(compressedImageFile.toPath());
}

And always when i run this compression for the first time it takes much longer than in next runs. My question is why is this happening ?

Upvotes: 0

Views: 192

Answers (1)

Harald K
Harald K

Reputation: 27084

As mentioned in the link I posted in the comments, this is common for all things Java:

The first time execution of anything Java is always going to be slower than subsequent runs. There is a startup-overhead, because...

Generally:

  • The first time a class is used, the class loader has to look up, load, verify and initialize the class.
  • The first time code is run, it is interpreted. Hotspot/the JIT will optimize it later, after some predefined threshold. If your code hits this threshold the first time (ie. loops), parts of it might be optimized on the first run, taking even more time.

The ImageIO class especially has to do a lot of things on start-up:

  • Service Provider lookup and instantiation of all available plug-ins. The more plug-ins available, the more time it will take.
  • Because it's a part of the Java Desktop module, it's likely that some parts of it or the plug-ins will trigger the initialization of the Java2D subsystem. Using the headless system property might help making this slightly faster.
  • The JPEG plug-in especially, uses native code, this also has to be loaded, initialized on the first execution.

(Plus, probably more things I didn't think of).

Upvotes: 1

Related Questions