简体   繁体   English

为什么ReSharper为C#代码反转IF? 它是否提供更好的性能(甚至略微)?

[英]Why does ReSharper invert IFs for C# code? Does it give better performance (even slightly)?

Consider the following code sample: 请考虑以下代码示例:

private void AddEnvelope(MailMessage mail)
{
    if (this.CopyEnvelope)
    {
        // Perform a few operations
    }
}

vs VS

private void AddEnvelope(MailMessage mail)
{
    if (!this.CopyEnvelope) return;
    // Perform a few operations
}

Will the bottom code execute any faster? 底部代码会执行得更快吗? Why would ReSharper make this recommendation? 为什么ReSharper会提出此建议?

Update 更新

Having thought about this question the answer might seem obvious to some. 考虑过这个问题后,答案对某些人来说似乎是显而易见的。 But lots of us developers were never in the habit of nesting zounds of if statements in the first place... 但是我们很多开发人员从来没有习惯在第一时间嵌套if语句...

It doesn't matter. 没关系。 Stop agonizing over performance issues that don't exist - use a profiler to identify areas in your code that DO exhibit issues, and fix them. 停止对不存在的性能问题感到痛苦 - 使用分析器来识别代码中出现问题的区域并修复它们。 Proactive optimization - before you know that there is a problem - is by definition a waste of time. 主动优化 - 在您知道存在问题之前 - 根据定义是浪费时间。

Updated Answer: 更新答案:

It's a code maintainability suggestion. 这是代码可维护性建议。 Easier to read than nesting the rest of the code in an IF statement. 比在IF语句中嵌套其余代码更容易阅读。 Examples/discussion of this can be seen at the following links: 有关这方面的示例/讨论可以在以下链接中看到:

Original Answer: 原答案:

It will actually run (very negligibly) slower from having to perform a NOT operation. 它实际上(必须非常可忽略地)从必须执行NOT操作开始运行。

So much in fact, some people actually consider that prettier way to code as it avoids an extra level of indentation for the bulk of the code. 实际上,有些人实际上考虑了更漂亮的代码方式,因为它避免了大量代码的额外缩进级别。

It's a refactor of a conditional that encompasses the entire method contents to a Guard Clause . 它是条件的重构,它将整个方法内容包含在Guard子句中 It has nothing to do with optimization. 它与优化无关。

I like the comments about optimizing things like this, to add a little more to it... 我喜欢关于优化这样的事情的评论,为它添加一点......

The only time I can think of that it makes sense to optimize your if statements is when you have the results of TWO or more longish running methods that need to be combined to determine to do something else. 唯一一次我能想到优化你的if语句是有意义的,当你有两个或更多长时间运行的方法的结果需要结合起来以确定做其他事情时。 You would only want to execute the second operation if the first operation yielded results that would pass the condition. 如果第一个操作产生了可以通过条件的结果,您只想执行第二个操作。 Putting the one that is most likely to return false first will generally be a smarter choice. 将最有可能首先返回假的那个放在首先通常是一个更明智的选择。 This is because if it is false, the second one will not be evaluated at all. 这是因为如果它是假的,则根本不会评估第二个。 Again, only worth worrying about if the operations are significant and you can predict which is more likely to pass or fail. 同样,只值得担心的是,如果操作是重要的,您可以预测哪个更有可能通过或失败。 Invert this for OR... if true, it will only evaluate the first, and so optimize that way. 将此反转为OR ...如果为true,则仅评估第一个,因此优化该方式。 ie

if (ThisOneUsuallyPasses() && ThisOneUsuallyFails())

isn't so good as 不是那么好

if (ThisOneUsuallyFails() && ThisOneUsuallyPasses())

because it's only on the odd case that the first one actually works that you have to look at the second. 因为只有在奇怪的情况下,第一个实际工作,你必须看第二个。 There's some other flavors of this you can derive, but I think you should get the point. 你可以得到一些其他的味道,但我认为你应该明白这一点。

Better to worry about how you use strings, collections, index your database, and allocate objects than spend a lot of time worrying about single condition if statements if you are worrying about perf. 最好担心如何使用字符串,集合,索引数据库和分配对象,而不是花费大量时间担心单个条件if语句,如果你担心perf。

In general, what the bottom code you give will do is give you an opportunity to avoid a huge block of code inside an if statement which can lead to silly typo driven errors. 一般来说,你给出的底层代码将会给你一个避免if语句中的大量代码块的机会,这可能导致错误的错误驱动错误。 Old school thinking was that you should only have one point that you return from a method to avoid a different breed of coder error. 老派的想法是,你应该只从一个方法返回一个点,以避免不同类型的编码器错误。 Current thinking (at least by some of the tool vendors such as jetbrains resharper, etc) seems to be that wrapping the least amount of code inside of conditional statements is better. 目前的想法(至少是一些工具供应商,如jetbrains resharper等)似乎是将条件语句中包含最少量的代码包装得更好。 Anything more than that would be subjective so I'll leave it at that. 除此之外的任何东西都是主观的,所以我会留下它。

This kind of "Optimizations" are not worth the time spent on refactoring your code, because all modern compilers does already enough small optimizations that they make this kind of tips trivial. 这种“优化”不值得花费在重构代码上的时间,因为所有现代编译器都已经进行了足够小的优化,使得这种技巧变得微不足道。 As mentioned above Performance Optimization is done through profilers to calculate how your system is performing and the potential bottlenecks before applying the performance fix, and then after the performance fix to see if your fix is any good. 如上所述,性能优化通过分析器完成,以计算系统的性能和应用性能修复之前的潜在瓶颈,然后在性能修复之后查看您的修复是否有用。

Required reading: Cyclomatic_complexity 必读: Cyclomatic_complexity

Cyclomatic Complexity is a quantitative measure of the number of linearly independent paths through a program's source code Cyclomatic Complexity是通过程序源代码的线性独立路径数量的定量度量

Which means, every time you branch using and if statement you increase the Cyclomatic Complexity by 1. 这意味着,每次使用和if语句分支时,都会将Cyclomatic Complexity提高1。

To test each linearly independent path through the program; 通过程序测试每个线性独立的路径; in this case, the number of test cases will equal the cyclomatic complexity of the program. 在这种情况下,测试用例的数量将等于程序的圈复杂度。

Which means, if you want to test your code completely, for each if statement you would have to introduce a new test case. 这意味着,如果要完全测试代码,对于每个if语句,您必须引入一个新的测试用例。

So, by introducing more if statements the complexity of your code increases, as does the number of test cases required to test it. 因此,通过引入更多if语句,代码的复杂性会增加,测试它所需的测试用例数也会增加。

By removing if statements, your code complexity decreases as does the number of test cases required to test. 通过删除if语句,您的代码复杂性会降低,测试所需的测试用例数if减少。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM