更好的是:多个“如果”陈述或一个“如果”有多个条件?

发布于 2024-10-21 08:45:45 字数 582 浏览 8 评论 0原文

对于我的工作,我必须开发一个小型 Java 应用程序,用于解析非常大的 XML 文件(约 300k 行)以选择非常具体的数据(使用 Pattern),因此我尝试对其进行一些优化。我想知道这两个片段之间哪个更好:

if (boolean_condition && matcher.find(string)) {
    ...
}

OR

if (boolean_condition) {
    if (matcher.find(string)) {
        ...
    }
}

其他细节:

  • 这些 if 语句在循环内的每次迭代中执行(~20k 迭代)
  • boolean_condition 是 <使用外部函数在每次迭代时计算 code>boolean
  • 如果 boolean 设置为 false,我不需要测试正则表达式的匹配

谢谢为了你的帮助。

For my work I have to develop a small Java application that parses very large XML files (~300k lines) to select very specific data (using Pattern), so I'm trying to optimize it a little. I was wondering what was better between these 2 snippets:

if (boolean_condition && matcher.find(string)) {
    ...
}

OR

if (boolean_condition) {
    if (matcher.find(string)) {
        ...
    }
}

Other details:

  • These if statements are executed on each iteration inside a loop (~20k iterations)
  • The boolean_condition is a boolean calculated on each iteration using an external function
  • If the boolean is set to false, I don't need to test the regular expression for matches

Thanks for your help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

时间你老了 2024-10-28 08:45:45

我遵循的一条黄金法则是尽可能“避免嵌套”。但如果这是以让我的单一 if 条件过于复杂为代价的,我不介意将其嵌套出来。

此外,您还使用短路 && 运算符。因此,如果布尔值为假,它甚至不会尝试匹配!

所以,

if (boolean_condition && matcher.find(string)) {
    ...
}

这就是要走的路!

One golden rule I follow is to "Avoid Nesting" as much as I can. But if it is at the cost of making my single if condition too complex, I don't mind nesting it out.

Besides you're using the short-circuit && operator. So if the boolean is false, it won't even try matching!

So,

if (boolean_condition && matcher.find(string)) {
    ...
}

is the way to go!

枫林﹌晚霞¤ 2024-10-28 08:45:45

以下两种方法:

public void oneIf(boolean a, boolean b)
{
    if (a && b)
    {   
    }
}

public void twoIfs(boolean a, boolean b)
{
    if (a)
    {
        if (b)
        {       
        }
    }
}

为方法体生成完全相同的字节代码,因此不会有任何性能差异,这意味着它纯粹是您使用的风格问题(我个人更喜欢第一种风格)。

The following two methods:

public void oneIf(boolean a, boolean b)
{
    if (a && b)
    {   
    }
}

public void twoIfs(boolean a, boolean b)
{
    if (a)
    {
        if (b)
        {       
        }
    }
}

produce the exact same byte code for the method body so there won't be any performance difference meaning it is purely a stylistic matter which you use (personally I prefer the first style).

月野兔 2024-10-28 08:45:45

两种方式都可以,如果第一个条件为 false,则不会测试第二个条件。

使用一种使代码更具可读性和易于理解的方法。对于仅两个条件,第一种方法更具逻辑性和可读性。如果使用 &&||! 链接 5 或 6 个条件,情况可能就不再是这样了。

Both ways are OK, and the second condition won't be tested if the first one is false.

Use the one that makes the code the more readable and understandable. For just two conditions, the first way is more logical and readable. It might not be the case anymore with 5 or 6 conditions linked with &&, || and !.

悲歌长辞 2024-10-28 08:45:45

我建议将您的表达式提取到语义上有意义的变量,然后将其传递给您的评估。而不是:

if (boolean_condition && matcher.find(string)) { ... }

将表达式分配给变量,然后计算该变量:

const hasItem = boolean_condition && matcher.find(string)

if (hasItem) { ... }

使用此方法,您甚至可以保持最复杂的计算的可读性:

const hasItem = boolean_condition && matcher.find(string)

const hasOtherThing = boolean_condition || boolean_condition

const isBeforeToday = new Date(string) < new Date()

if (hasItem && hasOtherThing && isBeforeToday) { ... }

I recommend extracting your expression to a semantically meaningful variable and then passing that to your evaluation. Instead of:

if (boolean_condition && matcher.find(string)) { ... }

Assign the expression to a variable, then evaluate the variable:

const hasItem = boolean_condition && matcher.find(string)

if (hasItem) { ... }

With this method, you can keep even the most complex evaluations readable:

const hasItem = boolean_condition && matcher.find(string)

const hasOtherThing = boolean_condition || boolean_condition

const isBeforeToday = new Date(string) < new Date()

if (hasItem && hasOtherThing && isBeforeToday) { ... }
粉红×色少女 2024-10-28 08:45:45

Java 对这些布尔运算符使用短路,因此这两种变体在功能上是相同的。因此,如果 boolean_condition 为 false,它将不会继续进行匹配。

最终,您会发现更容易阅读和调试,但如果您最终得到一个 如果条件变长

,提高可读性的一种方法是简单地将其分成多行:

if(boolean_condition &&
   matcher.find(string))
{
    ...
}

此时唯一的选择是是否将 && 放在最后。和 ||在上一行的末尾或当前行的开头。

Java uses short-circuiting for those boolean operators, so both variations are functionally identical. Therefore, if the boolean_condition is false, it will not continue on to the matching

Ultimately, it comes down to which you find easier to read and debug, but deep nesting can become unwieldy if you end up with a massive amount of braces at the end

One way you can improve the readability, should the condition become longer is to simply split it onto multiple lines:

if(boolean_condition &&
   matcher.find(string))
{
    ...
}

The only choice at that point is whether to put the && and || at the end of the previous line, or the start of the current.

予囚 2024-10-28 08:45:45

我倾向于看到太多 &&和 ||串在一起形成逻辑汤,并且通常是微妙错误的根源。

添加另一个 && 太容易了。或||到你认为正确的地方并打破现有的逻辑。

因此,作为一般规则,我尽量不使用其中任何一个,以避免随着需求变化而添加更多内容的诱惑。

I tend to see too many && and || strung together into a logic soup and are often the source of subtle bugs.

It is too easy to just add another && or || to what you think is the right spot and break existing logic.

Because of this as a general rule i try not to use either of them to avoid the temptation of adding more as requirements change.

蹲在坟头点根烟 2024-10-28 08:45:45

如果您想遵守声纳规则squid:S1066,您应该折叠 if 语句以避免警告,因为它指出:

应合并可折叠的“if”语句

If you like to be compliant to Sonar rule squid:S1066 you should collapse if statements to avoid warning since it states:

Collapsible "if" statements should be merged

没企图 2024-10-28 08:45:45

第一个。我尽量避免像这样嵌套,我认为这是糟糕的风格/丑陋的代码和 &&如果布尔值为 true,将短路并仅使用 matcher.find() 进行测试。

The first one. I try to avoid if nesting like that, i think it's poor style/ugly code and the && will shortcircuit and only test with matcher.find() if the boolean is true.

萌逼全场 2024-10-28 08:45:45

就性能而言,它们是相同的。

  • 但即使它们不是,

几乎可以肯定在这段代码中占主导地位的是 matcher.find(string) 因为它是一个函数调用。

In terms of performance, they're the same.

  • But even if they weren't

what's almost certain to dominate the time in this code is matcher.find(string) because it's a function call.

ゝ杯具 2024-10-28 08:45:45

大多数人更喜欢使用下面的,因为“&&”。

if (boolean_condition && matcher.find(string)) {
...
}

我们通常将其称为“短路(或最小评估)”。这意味着仅当第一个参数没有足够的信息来确定表达式的值时,才会计算第二个参数(此处为“matcher.find(string)”)。例如,如果“boolean_condition”为 false,则整体条件必须为 false(因为这里有逻辑 AND 运算符)。那么编译器将不会检查第二个参数,这将导致减少代码的运行时间。

Most would prefer to use the below one, because of "&&".

if (boolean_condition && matcher.find(string)) {
...
}

We normally called these as "short-circuit (or minimum evaluation)". It means the 2nd argument (here it is "matcher.find(string)") is only evaluated only if the 1st argument doesn't have sufficient information to determine the value of the expression. As an example, if the "boolean_condition" is false, then the overall condition must be false (because of here logical AND operator). Then compiler won't check the 2nd argument which will cause to reduce the running time of your code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文