Java if vs. try/catch overhead

后端 未结 5 1702
南旧
南旧 2020-11-27 13:33

Is there any overhead in Java for using a try/catch block, as opposed to an if block (assuming that the enclosed code otherwise does not re

5条回答
  •  萌比男神i
    2020-11-27 14:05

    As far as overhead goes, you can test for yourself:

    public class Overhead {
    
    public static void main(String[] args) {
        String testString = "";
    
        long startTimeTry = System.nanoTime();
        tryTrim(testString);
        long estimatedTimeTry = System.nanoTime() - startTimeTry;
    
        long startTimeIf = System.nanoTime();
        ifTrim(testString);
        long estimatedTimeIf = System.nanoTime() - startTimeIf;
    
        System.out.println("Try time:" + estimatedTimeTry);
        System.out.println("If time:" + estimatedTimeIf);
    
    }
    
    public static String tryTrim(String raw) {
        try {
            return raw.trim();
        } catch (Exception e) {
        }
        return null;
    }
    
    public static String ifTrim(String raw) {
        if (raw == null) {
            return null;
        }
        return raw.trim();
    }
    

    }

    The numbers I got are:

    Try time:8102
    If time:1956
    

    As far as what style - it is a whole separate question. The if statement looks pretty natural, but the try looks really strange for multiple reason: - you caught Exception even though you are checking for NULL value, are you expecting something "exceptional" to happen (otherwise catch NullException)? - you caught that Exception, are you going to report it or swallow? etc. etc. etc.

    Edit: See my comment for why this is an invalid test, but I really didn't want to leave this standing here. Just by swapping tryTrim and ifTrim, we suddenly get the following results (on my machine):

    Try time:2043
    If time:6810
    

    Instead of starting to explain all of this, just read this for the beginning - Cliff also has some great slides about the whole topic, but I can't find the link at the moment.

    Knowing how exception handling works in Hotspot, I'm fairly certain that in a correct test try/catch without an exception) would be the baseline performance (because there's no overhead whatsoever), but the JIT can play some tricks with Nullpointer checks followed by method invocations (no explicit check, but catch the hw exception if the object is null) in which case we'd get the same result. Also don't forget: We're talking about the difference of one easily predictable if which would be ONE CPU cycle! The trim call will cost a million times that.

提交回复
热议问题