else or return?

后端 未结 19 579
故里飘歌
故里飘歌 2021-01-01 13:27

Which one out of following two is best wrt to performance and standard practice. How does .NET internally handles these two code snippets?

Code1

If(r         


        
相关标签:
19条回答
  • 2021-01-01 13:53

    If there is common code, that needs to be executed after the if/else block, then option 1.

    If the if-else block is the last thing to do in a function, then option 2.

    Personally I always use option 1. If there is a return stateent, it comes after the else block

    0 讨论(0)
  • 2021-01-01 13:54

    It depends on the context.

    If this is in a function that at calculating a value, return that value as soon as you have it (option 2). You are showing you have done all the work you need to, and are leaving.

    If this is code that is part of program logic then it's best to be as precise as possible (option 1). Someone looking at option 1 will know you mean (do this OR that), where as option 2 could be a mistake (in this condition do this THEN ALWAYS do that - I'll just correct it for you!). Had that before.

    When compiled these will be usually the same, but we are not interested in performance. This is about readability and maintainable.

    0 讨论(0)
  • 2021-01-01 13:55

    I tend to have a single point of exit, which is very useful when implementing locks in a multi-threaded environment, to make sure that the locks are released. With the first implementation, it's harder to do.

    0 讨论(0)
  • 2021-01-01 13:56

    I think you should't worry about performance here. In this case readability and maintainability are way more important.

    Sticking to one exit point for a routine is a good practice.

    However, sometimes multiple returns just make the code a lot clearer, especially when you have a number of tests near the beginning of the code (ie checking if all of the input parameters are in the correct format) for which an 'if-true' should lead to a return.

    ie:

    if (date not set) return false;
    age = calculateAgeBasedOnDate();
    if (age higher than 100) return false;
    ...lots of code...
    return result;
    
    0 讨论(0)
  • 2021-01-01 13:58

    Personally I always like to return ASAP so I would go for something like:

    if (result)
    {
        // do something
        return;
    }
    
    // do something if not result
    

    With regards to performance, I doubt either have any advantages over eachother it really comes down to readability and personal taste. I assume .NET would optimize your first code block to something like the above.

    0 讨论(0)
  • 2021-01-01 13:58

    Can't say about performance, but Code 1 looks a lot clearer and more logical to me. Jumping out of a function in the middle of an if block appears quite confusing and is easy to overlook.

    0 讨论(0)
提交回复
热议问题