jeudi 21 mai 2015

One long If condition vs. many smaller conditions with checkpoints

TLDR: What is better: a long if...else that has lots of similar code throughout each of the conditions or many smaller if...else statements with multiple checkpoints.

This is a question that may extend to many languages, but JavaScript is where I am applying this idea immediately.

In optimizing my JS, I have come across one massive if...else condition. Both the if and the else share some code where they execute a certain function based on a variable determined by the condition and then continue on to condition-specific functions. Here's an example:

var w  = $(window).width();

if (w > 1024) {

    var ww        = w/2;
    $(".container").width(ww);

    foo(); // represents long, in-common set of functions

    var imgWidth  = ww/3;
    $(".container img").width(imgWidth);

} else {

    var ww        = w/3;
    $(".container").width(ww);

    foo(); // represents long, in-common set of functions

    var imgWidth  = ww/4;
    $(".container img").width(imgWidth);

}

foo() representing a common midpoint/checkpointfunction that may be irrelevant to the value of the variables being declared but is essentially dependent upon them being executed. In my actual code, the foo() represents many common functions happening consecutively, forcing me to either write one massive if...else or many smaller checks along the way. My question is, is this a better/faster way:

var w  = $(window).width();

if (w > 1024) {

    var ww        = w/2;
    $(".container").width(ww);

} else {

    var ww        = w/3;
    $(".container").width(ww);
}

foo(); // represents a checkpoint with long, in-common sets of functions

if (w > 1024) {

    var imgWidth  = ww/3;
    $(".container img).width(imgWidth);

} else {

    var imgWidth  = ww/4;
    $(".container img).width(imgWidth);

}

Visually, I understand this to be a competition between these two models: enter image description here

I understand either may create a larger file size if these functions get complex and have many common checkpoints, but performance is valued far more here than a few extra bytes. What's better (faster)?

Aucun commentaire:

Enregistrer un commentaire