LeGaulois88
LeGaulois88

Reputation: 99

Is it faster to write Images into a new file or to copy them?

I'm currently developping a software which uses images. The soft loads them from the HD and uses them but it doesn't modify them.

Consequently, I have some Images instanciated into the RAM. In a particular case, I have to write those pictures on the hard drive (but in a different directory than their original location).

Actually, I do not know what is the most efficient way to do this. Is it faster to copy a file from one folder to another one (with Files.copy()) or should I write my RAM-loaded pictures into a new file (using a BufferedWriter for exemple)?

In my opinion, writing a new file from loaded pictures could be faster because it doesn't have to read a file on the HD. However, I'm not sure about it and I don't know what is the real process behind Files.copy().

Can anyone help me?

Thanks.

Upvotes: 2

Views: 689

Answers (2)

maaartinus
maaartinus

Reputation: 46432

I'd bet that copying is usually faster.

  • If you're lucky, the image is buffered by the OS and you don't really access the disk for reading it, so the advantage of writing from memory vanishes.

  • Any sane image format (and I don't mean BMP) is compressed and an image in memory is not (you want to work with it, right?). And compression is a rather slow operation.

That all said, only a measurement can tell you for sure.


I used a JPG for my benchmark, as it's a computationally expensive format.

private void go() throws Exception {
    final BufferedImage image = ImageIO.read(src);
    for (int i=0; i<100; ++i) {
        write(image);
        copy();
    }
}

private void write(BufferedImage image) throws Exception {
    final long start = System.nanoTime();
    ImageIO.write(image, "jpg", dst);
    final long end = System.nanoTime();
    System.out.format("write %15.6f\n", 1e-9 * (end-start));
}

private void copy() throws Exception {
    final long start = System.nanoTime();
    Files.copy(src.toPath(), dst.toPath(), StandardCopyOption.REPLACE_EXISTING);
    final long end = System.nanoTime();
    System.out.format("copy  %15.6f\n", 1e-9 * (end-start));
}

The results are as follows

write        0.200160
copy         0.001850
write        0.200056
copy         0.001886

So copying wins by two order of magnitude. Whoever claims that using JPG is unfair should do their own tests.

Upvotes: 2

chokdee
chokdee

Reputation: 456

It is faster to store the RAM loaded Image to the file system because you don't have to read it again from the filesystem.

Upvotes: 0

Related Questions