0

So I am writing a program which reads logs from different files, sorts them by a given status and outputs them to the accordingly files. There are approx. 8-10k logs at any time and I currently have this wile loop to check their status :

    private void SortByStatus(TreeSet<Log> allLogs) {
    Iterator<Log> iter = allLogs.iterator();
    while(iter.hasNext()){
        Log temp = iter.next();
        if(temp.getLogStatus() == Log.Status.INFO)
            INFOlogs.add(temp);
        if(temp.getLogStatus() == Log.Status.WARN)
            WARNlogs.add(temp);
        if(temp.getLogStatus() == Log.Status.DEBUG)
            DEBUGlogs.add(temp);
        if(temp.getLogStatus() == Log.Status.ERROR)
            ERRORlogs.add(temp);
    }
}

I was just wondering if this can be improved in any way, even marginally faster would be nice if possible

Thanks in advance

  • Using if-else-if is more efficient as it stops comparing once it found the correct one. Switch is more readable if the statement are numerous. – PSo Feb 02 '17 at 10:45
  • 2
    Actually switch .. case is the recommended way to handle these situations – A Nice Guy Feb 02 '17 at 10:45
  • NOTE: adding a switch statement seemed not to improve the speed, which I forgot to mention – Jim Vekemans Feb 02 '17 at 10:49
  • @JimVekemans you should look for something else to improve, because there's not much to do here. Check that you're using buffers to output to files for example, I/O has a much bigger impact on performances than bad code. – Aaron Feb 02 '17 at 10:52
  • 1
    switch .. case is known to improve speed, maybe you didnt check with enough test data? http://stackoverflow.com/questions/2158759/case-vs-if-else-if-which-is-more-efficient – A Nice Guy Feb 02 '17 at 11:04

1 Answers1

0

Your if statements could be fused into a switch/case statement :

private void SortByStatus(TreeSet<Log> allLogs) {
    Iterator<Log> iter = allLogs.iterator();
    while(iter.hasNext()){
        Log temp = iter.next();
        switch(temp.getLogStatus()) {
            case Log.Status.INFO :
                INFOlogs.add(temp);
                break;
            case Log.Status.WARN :
                WARNlogs.add(temp);
                break;
            case Log.Status.DEBUG :
                DEBUGlogs.add(temp);
                break;
            case Log.Status.ERROR :
                ERRORlogs.add(temp);
                break;
            default :
                // do nothing? raise error?
    } 
}

The performance gain will be minimal but this will avoid executing 4 tests when the log level is INFO (which would also have been avoided by the use of else if statements).

Aaron
  • 24,009
  • 2
  • 33
  • 57