This is a question that lives in my mind from a long time.

Does the use of multiple nested conditional statements impact the performance of a taken code? So far I know that programmers have created a precise term to describe this situation, the in-famous "Pyramid of doom" [Wikipedia page], but a side from that how much can this degrade performances?

Let's take this situation as an example: I have a JSON coming from a server response containing a few objects that represent the user purchases in an application, before taking the needed data from it I need to check various conditions:

  1. Is the response we are looking for?
  2. Does response has resultCode: OK?
  3. Are the any contents to process?

At this point if everything is true a "processing process" will begin, parsing and editing the server response, in this case for changing the date format from US to the standard european format. The process consist in two nested for-loops and an if statement.

This is the example code in Objective-C, since I'm an iOS Developer:

if ([remoteManager.operationId isEqualToString:NEEDED_OPERATION_ID]) {
    if ([response[RESULT_CODE_KEY] isEqualToString:@"OK"]) {
        if ([response[RESULT_OBJ_KEY][@"CONTENT_LIST"] count] > 0) {
            NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];

            for (NSMutableDictionary *productsAvailable in response[RESULT_OBJ_KEY][@"CONTENT_LIST"]) {
                for (NSString *key in productsAvailable) {
                    if ([key isEqualToString:@"NEEDED_KEY"]) {
                        /* We change the date format here */
                    }
                }
            }
        }
    }
}

In my opining this code can't really have an impact on the performance of an application because those checks are not so complicated for the system to do. But does this can be a problem if we need to have the maximum speed and performances? In other words: should nested conditionals be avoided or not? And also does putting multiple conditions at the same time reduces the performance problems (if any)?

有帮助吗?

解决方案

The sequence of steps that you described appears to be a sequence of steps that you must perform, in order for your application to achieve what it is supposed to achieve. So, there is nothing that you could add or remove.

With the existing code, you have the following options:

  • Rearrange the order in which the conditionals are evaluated. You could, perhaps, achieve better performance by re-arranging the conditionals so that the most frequently failing ones are evaluated first, or so that the more computationally expensive ones are evaluated last, but it is hardly worth the effort, and in any case you need to spend some time measuring stuff before you attempt that, otherwise you are shotgunning the problem and running the danger of worsening things instead of improving things.

  • Replace nesting with multiple expressions ANDed together. I know nothing of Objective-C, but I would be willing to bet that it stays true to the tradition of C, and it uses short-circuit boolean expression evaluation, so the construct if(a) { if(b) { ... } } is equivalent to if((a) && (b)) { ... }, so nesting or no nesting makes absolutely no difference.

  • Replace nesting with early-exiting. Early exiting is when you say if(!a) return; if(!b) return; bulk-of-code-goes-here. There are people who insist on early exiting, so as to reduce the nesting, and others who see no problem with nesting, and believe that early exiting is evil. But again, this makes no difference on how fast the code will run, so this issue is all about style, not performance: "to nest or not to nest" is an entirely subjective question which can only receive a subjective answer. (Which is of course "die, you nesting fool !")

So, there is pretty much nothing you can do to improve things, and nesting or no nesting has absolutely no impact on performance. On top of that, no matter how you structure your conditionals, the compiler is generally free to emit the machine code in whatever way it sees fit, as long as it has the same result, so your nested conditionals will probably be implemented as early exits by the compiler, just as short-circuit evaluation would. This means that at the end of the day, the only criterion for how to arrange your conditionals ought to be how it is most natural for you to read them and understand them.

I would recommend that you heed the advice contained in gnat's excellent (and ironic) suggestion that your question is a duplicate of another question which is in fact about micro-optimizations: stop worrying about performance of code. You should only start being worried about performance if your final product is found to actually suffer performance-wise, and even then, the solutions that you will find will most likely be algorithmic, big-picture optimizations, and it is highly unlikely that they will have anything to do with how you order individual instructions.

其他提示

The problem with nested conditions is not speed, its human comprehension.

Human beings have trouble coping with many possibilities at once. They reach their limit (which is fairly small) then start to make mistakes without realising it.

Conditional statements increase complexity fairly quickly: 2, 4, 8, 16, 32, 64, 128... and for almost all programmers, the limit is in single digits.

Computers have no problems optimising code with very many nested conditions, but humans will find it almost impossible to maintain the source code - which means it won't work.

Most programming techniques are about coping with human weakness, rather than speed. Source code is for humans.

许可以下: CC-BY-SA归因
scroll top