How expensive is File.exists in Java

Viewed 13211

I am wondering how File.exists() works. I'm not very aware of how filesystems work, so I should maybe start reading there first.

But for a quick pre information:

Is a call to File.exists() a single action for the filesystem, if that path and filename are registered in some journal? Or does the OS get the content of the directory and then scan through it for matches?

I presume this will be filesystem dependent, but maybe all filesystems use the quick approach?

I'm not talking about network and tape systems. Lets keep it to ntfs, extX, zfs, jfs :-)

4 Answers

It's super fast on any modern machine, my tests show 0.0028 millis (2.8 microseconds) on my 2013 Mac w/SSD

1,000 files created in 307 millis, 0.0307 millis per file

1,000 .exists() done in 28 millis, 0.0028 millis per file

Here's a test in Groovy (Java)

def index() {
    File fileWrite

    long start = System.currentTimeMillis()

    (1..1000).each {
        fileWrite = new File("/tmp/fileSpeedTest/${it}.txt")
        fileWrite.write('Some nice text')
    }
    long diff = System.currentTimeMillis() - start
    println "1,000 files created in $diff millis, ${diff/10000.0} millis per file"



    start = System.currentTimeMillis()
    (1..1000).each {
        fileWrite = new File("/tmp/fileSpeedTest/${it}.txt")
        if ( ! fileWrite.exists() )
            throw new Exception("where's the file")
    }
    diff = System.currentTimeMillis() - start
    println "1,000 .exists()   done in  $diff millis, ${diff/10000.0} millis per file"

}
Related