Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Arrays.sort() Taking a Long Time

Tags:

java

sorting

I am using Java's Arrays.sort() function to sort a list of files by their last modified time. The sort for 245 files is taking around 5 seconds. This seems too long to me. I feel it shouldn't take more than 0.5 seconds. Is that a good assumption? What am I doing wrong? OR does this sound normal?

public static class LastModifiedComparator implements Comparator<File> {
    @Override
    public int compare(File f1, File f2) {
        return (int)(f1.lastModified() - f2.lastModified());
    }       
}

File folder = new File( "C:\\Whatever\\" );
File[] filesInFolder = folder.listFiles();
logger.debug("Starting File Sort");
Arrays.sort(filesInFolder, new LastModifiedComparator());
logger.debug("Done File Sort");

Output in Log

2012-08-10 14:24:20,333 DEBUG http-8080-4 <ClassName>:73 - Starting File Sort
2012-08-10 14:24:25,915 DEBUG http-8080-4 <ClassName>:75 - Done File Sort
like image 266
Danish Avatar asked Aug 10 '12 18:08

Danish


1 Answers

You will need to improve your Comparator logic. You need to cache the lastModified() values because the implementation of that method is quite slow. I suggest wrapping the File instances into a comparable object of your making that will cache the value:

public class FileLmWrapper implements Comparable<FileLmWrapper> {
  public final File f;
  public final long lastModified;
  public FileLmWrapper(File f) { 
    this.f = f; 
    lastModified = f.lastModified();
  }
  public int compareTo(FileLmWrapper other) {
    return Long.compare(this.lastModified, other.lastModified);
  }
}
like image 129
Marko Topolnik Avatar answered Sep 27 '22 15:09

Marko Topolnik