//
// FileOpsTest.java
//

import java.io.File;

/** Tests performance of File.exists() vs File.listFiles(). */
public class FileOpsTest {
  public static void main(String[] args) {
    int iter = 1000;
    if (args.length > 0) iter = Integer.parseInt(args[0]);
    long t1, t2;

    File dot = new File(".");
    File[] list = dot.listFiles();

    // time File.exists with an existing file
    t1 = System.currentTimeMillis();
    for (int i=0; i<iter; i++) list[i % list.length].exists();
    t2 = System.currentTimeMillis();
    System.out.println("File.exists() for existing = " + (t2 - t1) + " ms");

    // time File.exists with a non-existent file
    File non = new File("this-file-is-unlikely-to-exist");
    t1 = System.currentTimeMillis();
    for (int i=0; i<iter; i++) non.exists();
    t2 = System.currentTimeMillis();
    System.out.println("File.exists() for non-exist = " + (t2 - t1) + " ms");

    // time File.listFiles
    t1 = System.currentTimeMillis();
    for (int i=0; i<iter; i++) dot.listFiles();
    t2 = System.currentTimeMillis();
    System.out.println("File.listFiles() = " + (t2 - t1) +
      " ms (" + ((t2 - t1) / list.length) + "/file)");
  }
}

@@ -1175,8 +1175,1155 @@
 ;%0A  %7D%0A%7D%0A
+%0A/*%0ASome results on a MacPro 2 x 2.66 GHz Dual-Core Intel Xeon%0ANetworked file system over SMB on local network (gigabit?)%0AWindows and Linux results via Parallels v2%0A%0ALINUX - NETWORK%0AFile.exists() for existing = 16 ms%0AFile.exists() for non-exist = 12 ms%0AFile.listFiles() = 1755 ms (2/file)%0A%0AMAC OS X - NETWORK%0Acurtis@monk:~/data/perkinelmer/koen/20061107165034$ java FileOpsTest%0AFile.exists() for existing = 58 ms%0AFile.exists() for non-exist = 602 ms%0AFile.listFiles() = 4519 ms (6/file)%0A%0AWIN XP - NETWORK%0AZ:%5Cperkinelmer%5Ckoen%5C20061107165034%3Ejava -cp C:%5Csvn%5Cjava%5Cutils FileOpsTest%0AFile.exists() for existing = 2043 ms%0AFile.exists() for non-exist = 1763 ms%0AFile.listFiles() = 40882 ms (60/file)%0A%0ALINUX - LOCAL%0AFile.exists() for existing = 10 ms%0AFile.exists() for non-exist = 17 ms%0AFile.listFiles() = 71 ms (2/file)%0A%0AMAC OS X - LOCAL%0Acurtis@monk:~/svn/java/jar$ java FileOpsTest%0AFile.exists() for existing = 7 ms%0AFile.exists() for non-exist = 12 ms%0AFile.listFiles() = 149 ms (5/file)%0A%0AWIN XP - LOCAL%0AC:%5Csvn%5Cjava%5Cjar%3Ejava -cp ..%5Cutils FileOpsTest%0AFile.exists() for existing = 0 ms%0AFile.exists() for non-exist = 0 ms%0AFile.listFiles() = 91 ms (3/file)%0A*/%0A

Add comment with some results.