在 Java 中使用 break 退出循环是不好的做法吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18188123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:07:57  来源:igfitidea点击:

Is it bad practice to use break to exit a loop in Java?

javaloopsjvmbreak

提问by Don

I was wondering if it is a "bad practice" to use a breakstatement to exit a loop instead of fulfilling the loop condition?

我想知道使用break语句退出循环而不是满足循环条件是否是“不好的做法” ?

I do not have enough insight in Java and the JVM to know how a loop is handled, so I was wondering if I was overlooking something critical by doing so.

我对 Java 和 JVM 没有足够的了解来了解循环是如何处理的,所以我想知道这样做是否忽略了一些关键的东西。

The focus of this question: is there a specific performance overhead?

这个问题的重点:有没有具体的性能开销?

采纳答案by christopher

Good lord no. Sometimes there is a possibility that something can occur in the loop that satisfies the overall requirement, without satisfying the logical loop condition. In that case, breakis used, to stop you cycling around a loop pointlessly.

好主没有。有时,循环中可能会出现满足总体要求的情况,但不满足逻辑循环条件。在这种情况下,break用于阻止您毫无意义地循环循环。

Example

例子

String item;

for(int x = 0; x < 10; x++)
{
    // Linear search.
    if(array[x].equals("Item I am looking for"))
    {
       //you've found the item. Let's stop.
       item = array[x];
       break; 
    }
}

What makes more sense in this example. Continue looping to 10 every time, even after you've found it, or loop until you find the item and stop? Or to put it into real world terms; when you find your keys, do you keep looking?

在这个例子中什么更有意义。每次都继续循环到 10,即使在您找到它之后,还是循环直到找到该项目并停止?或者把它变成现实世界的术语;当你找到你的钥匙时,你会继续寻找吗?

Edit in response to comment

编辑以回应评论

Why not set xto 11to break the loop? It's pointless. We've got break! Unless your code is making the assumption that xis definitely larger than 10later on (and it probably shouldn't be) then you're fine just using break.

为什么不设置x11打破循环?没有用。我们有break!除非您的代码做出的假设x肯定比10稍后更大(并且可能不应该如此),否则您只需使用break.

Edit for the sake of completeness

为了完整起见进行编辑

There are definitely other ways to simulate break. For example, adding extra logic to your termination condition in your loop. Saying that it is either loop pointlessly or use breakisn't fair. As pointed out, a while loop can often achieve similar functionality. For example, following the above example..

肯定还有其他方法可以模拟break。例如,为循环中的终止条件添加额外的逻辑。说它要么毫无意义地循环要么使用break是不公平的。正如所指出的,while 循环通常可以实现类似的功能。例如,按照上面的例子..

while(x < 10 && item == null)
{
    if(array[x].equals("Item I am looking for"))
    {
        item = array[x];
    }

    x++;
}

Using breaksimply means you can achieve this functionality with a forloop. It also means you don't have to keep adding in conditions into your termination logic, whenever you want the loop to behave differently. For example.

使用break简单意味着您可以通过for循环实现此功能。这也意味着无论何时您希望循环的行为不同,您都不必在终止逻辑中不断添加条件。例如。

for(int x = 0; x < 10; x++)
{
   if(array[x].equals("Something that will make me want to cancel"))
   {
       break;
   }
   else if(array[x].equals("Something else that will make me want to cancel"))
   {
       break;
   }
   else if(array[x].equals("This is what I want"))
   {
       item = array[x];
   }
}

Rather than a while loopwith a termination condition that looks like this:

而不是while loop具有如下所示的终止条件:

while(x < 10 && !array[x].equals("Something that will make me want to cancel") && 
                !array[x].equals("Something else that will make me want to cancel"))

回答by user2550754

No, it is not a bad practice. It is the most easiest and efficient way.

不,这不是一个坏习惯。这是最简单有效的方法。

回答by nanofarad

The JLS specifies a break is an abnormal termination of a loop. However, just because it is considered abnormal does not mean that it is not used in many different code examples, projects, products, space shuttles, etc. The JVM specification does not state either an existence or absence of a performance loss, though it is clear code execution will continue after the loop.

JLS 指定中断是循环的异常终止。然而,仅仅因为它被认为是异常的,并不意味着它不会在许多不同的代码示例、项目、产品、航天飞机等中使用。JVM 规范没有说明是否存在性能损失,尽管它是清除代码执行将在循环后继续。

However, code readability can suffer with odd breaks. If you're sticking a break in a complex if statement surrounded by side effects and odd cleanup code, with possibly a multilevel break with a label(or worse, with a strange set of exit conditions one after the other), it's not going to be easy to read for anyone.

但是,代码可读性可能会因奇怪的中断而受到影响。如果您在被副作用和奇怪的清理代码包围的复杂 if 语句中插入一个中断,可能是一个带有标签的多级中断(或者更糟的是,一个接一个地使用一组奇怪的退出条件),它不会任何人都易于阅读。

If you want to break your loop by forcing the iteration variable to be outside the iteration range, or by otherwise introducing a not-necessarily-direct way of exiting, it's less readable than break.

如果您想通过强制迭代变量超出迭代范围来中断循环,或者以其他方式引入不必要的直接退出方式,那么它的可读性不如break.

However, looping extra times in an empty manner is almostalways bad practice as it takes extra iterations and may be unclear.

然而,以空的方式循环额外的次数几乎总是不好的做法,因为它需要额外的迭代并且可能不清楚。

回答by Marko Topolnik

Using break, just as practically any other language feature, canbe a bad practice, within a specific context, where you are clearly misusing it. But some very important idioms cannot be coded without it, or at least would result in far less readable code. In those cases, breakis the way to go.

使用break,就像实际上任何其他语言功能一样,在特定上下文中可能是一种不好的做法,在这种情况下,您显然是在滥用它。但是一些非常重要的习语没有它就无法编码,或者至少会导致代码可读性大大降低。在这些情况下,break是要走的路。

In other words, don't listen to any blanket, unqualified advice—about breakor anything else. It is not once that I've seen code totally emaciated just to literally enforce a "good practice".

换句话说,不要听信任何笼统的、不合格的建议——关于break或其他任何事情。我不止一次看到代码完全憔悴,只是为了从字面上强制执行“良好实践”。

Regarding your concern about performance overhead, there is absolutely none. At the bytecode level there are no explicit loop constructs anyway: all flow control is implemented in terms of conditional jumps.

关于您对性能开销的担忧,绝对没有。在字节码级别,无论如何都没有显式的循环结构:所有流控制都是根据条件跳转实现的。

回答by Ankur Shanbhag

No, it is not a bad practice to break out of a loop when if certain desired condition is reached(like a match is found). Many times, you may want to stop iterations because you have already achieved what you want, and there is no point iterating further. But, be careful to make sure you are not accidentally missing something or breaking out when not required.

不,如果达到某些所需条件(例如找到匹配项),则跳出循环并不是一个坏习惯。很多时候,你可能想要停止迭代,因为你已经实现了你想要的,没有必要再继续迭代。但是,请小心确保您不会意外丢失某些东西或在不需要时崩溃。

This can also add to performance improvementif you break the loop, instead of iterating over thousands of records even if the purpose of the loop is complete(i.e. may be to match required record is already done).

如果您打破循环,这也可以增加性能改进,而不是迭代数千条记录,即使循环的目的已经完成(即可能匹配所需的记录已经完成)。

Example :

例子 :

for (int j = 0; j < type.size(); j++) {
        if (condition) {
            // do stuff after which you want 

            break; // stop further iteration
        }

}

回答by bluehallu

Using break in loops can be perfectly legitimate and it can even be the only way to solve some problems.

使用 break in loop 可以是完全合法的,它甚至可以是解决某些问题的唯一方法。

However, it's bad reputation comes from the fact that new programmers usually abuse it, leading to confusing code, especially by using break to stop the loop in conditions that could have been written in the loop condition statement in the first place.

然而,它的坏名声来自这样一个事实,即新程序员通常滥用它,导致代码混乱,特别是通过使用 break 来停止循环,而这些条件本来可以写在循环条件语句中。

回答by Avery

While its not bad practice to use break and there are many excellent uses for it, it should not be all you rely upon. Almost any use of a break can be written into the loop condition. Code is far more readable when real conditions are used, but in the case of a long-running or infinite loop, breaks make perfect sense. They also make sense when searching for data, as shown above.

虽然使用 break 是一种不错的做法,并且它有许多出色的用途,但它不应该是您所依赖的全部。几乎任何中断的使用都可以写入循环条件。当使用真实条件时,代码的可读性要高得多,但在长时间运行或无限循环的情况下,中断是非常有意义的。它们在搜索数据时也很有意义,如上所示。

回答by peterp

If you know in advance where the loop will have to stop, it will probably improve code readability to state the condition in the for, while, or `do-whileloop.

如果事先知道循环将不得不停止,它可能会提高代码的可读性陈述的条件forwhile`do-while循环。

Otherwise, that's the exact use case for break.

否则,这就是break.

回答by robjohncox

It isn't bad practice, but it can make code less readable. One useful refactoring to work around this is to move the loop to a separate method, and then use a return statement instead of a break, for example this (example lifted from @Chris's answer):

这不是坏习惯,但它会使代码的可读性降低。解决这个问题的一个有用的重构是将循环移动到一个单独的方法,然后使用 return 语句而不是中断,例如这个(示例来自@Chris 的回答):

String item;

for(int x = 0; x < 10; x++)
{
    // Linear search.
    if(array[x].equals("Item I am looking for"))
    {
        //you've found the item. Let's stop.
        item = array[x];
        break; 
    }
}

can be refactored (using extract method) to this:

可以重构(使用提取方法)到这个:

public String searchForItem(String itemIamLookingFor)
{
    for(int x = 0; x < 10; x++)
    {
        if(array[x].equals(itemIamLookingFor))
        {
            return array[x];
        }
    }
}

Which when called from the surrounding code can prove to be more readable.

当从周围的代码中调用时,可以证明它更具可读性。

回答by Mik378

breakand continuebreaks the readability for the reader, although it's often useful. Not as much as "goto" concept, but almost.

breakcontinue破坏了读者的可读性,尽管它通常很有用。不像“goto”概念那么多,但差不多。

Besides, if you take some new languages like Scala (inspired by Java and functional programming languages like Ocaml), you will notice that breakand continuesimply disappeared.

此外,如果你使用一些像 Scala 这样的新语言(受 Java 和 Ocaml 等函数式编程语言的启发),你会注意到这一点,break然后continue就消失了。

Especially in functional programming, this style of code is avoided:

特别是在函数式编程中,避免了这种风格的代码:

Why scala doesn't support break and continue?

为什么scala不支持break和continue?

To sum up: breakand continueare widely used in Java for an imperative style, but for any coders that used to practice functional programming, it might be.. weird.

总结一下:breakandcontinue在 Java 中广泛用于命令式风格,但对于任何曾经练习函数式编程的编码人员来说,它可能......很奇怪。