mercredi 30 décembre 2015

Java: try-catch vs if-else for initialization: performance

I've heard it's a sin to use try-catch for anything that might be expected to happen in normal program flow, and that one should use if-else instead.

But, what about the case where we want to use it for initialization (an event that happens once and once only). You may want this when you initialization depends on the first incoming data, as in the following example:

class RunningVectorSum{

    double[] running_sum;

    public double[] add(double vec[]){

        try{
            for (int i=0; i<running_sum.length; i++)
                running_sum[i]+=vec[i];
        }
        catch(NullPointerException ex){
            running_sum = new double[vec.length];
            for (int i=0; i<running_sum.length; i++)
                running_sum[i] = vec[i];
        }
        return running_sum;
    }
}

In this case, should it be faster in the long run to use the try-catch vs using:

    public double[] add(double vec[]){
        if (running_sum==null)
            running_sum = new double[vec.length];
        for (int i=0; i<running_sum.length; i++)
            running_sum[i]+=vec[i];
        return running_sum;
    }

instead?

edit: Things I'm aware of:

  • Yes in this particular example, there's a possible problem if vec has a varying length
  • Yes I know this is a terrible sin.

Things I'm not aware of:

  • Why is it such a terrible sin?
  • Is it faster to always pass through a try (except once, which amortizes to nothing) than it is to always pass through an if(condition)

Aucun commentaire:

Enregistrer un commentaire