如何重构这个 GOTO(不涉及资源重新分配)?
这是一个简单的控制流 GOTO 问题,与资源分配无关。
检查一条数据是否“良好”有两个级别。如果且仅它通过了第一次检查,我们才会进行第二次检查。如果数据未通过任一测试,我们将使用默认值。
第二次检查涉及中间数据的几个步骤,因此我们不能将其置于短路的 ||
条件下。此外,如果第二个测试通过,我们将使用第二个测试的输出而不是原始数据。
这是实时处理情况下的内循环,所以效率非常重要。我们不想多次执行任何计算。
if (firstCheck(data)) {
result = analyze(data);
if (secondCheck(result)) {
use_result(result);
}
else {
goto FAIL;
}
}
else {
FAIL:
use_result(DEFAULT_VALUE);
}
这个GOTO似乎以最大的效率满足了我的所有要求。我可以想到其他一些方法来做到这一点,但所有方法都将涉及额外的存储或条件。不过我对 GOTO 持谨慎态度。事实上,如果我使用这个,这将是我第一次使用 GOTO。所以,请帮我找到出路!
This is a simple control-flow GOTO question, nothing about resource allocation.
There are two levels of checking if a piece of data is "good". If and only if it passes the first check, we do the second check. If the data fails either test, we use a default value instead.
The second check involves a few steps with intermediate data, so we can't just put it in a short-circuited ||
condition. Furthermore, if the second test passes, we use the output of the second test instead of the original data.
This is the inner loop in a real-time processing situation, so efficiency is very important. We don't want to do any of the calculations more than once.
if (firstCheck(data)) {
result = analyze(data);
if (secondCheck(result)) {
use_result(result);
}
else {
goto FAIL;
}
}
else {
FAIL:
use_result(DEFAULT_VALUE);
}
This GOTO seems to satisfy all my requirements with maximal efficiency. I can think of some other ways to do it, but all would involve extra storage or conditionals. I am wary of GOTOs though. In fact, if I use this, it will be the first time I have ever used a GOTO. So please, help me find the way out!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
continue
进入下一个循环迭代Use
continue
to go to next loop iteration好吧,我们不需要太多工作就可以解决这个问题,但是以这种方式使用 goto 不一定是坏行为 - 例如,linux 内核也使用此约定仅在一个位置进行错误处理,我认为代码非常清晰。
使用异常来解决这个问题显然是一种解决方案,但这在错误情况下会降低性能,所以我认为这是不可能的。
所以如果你愿意的话,这应该没问题:
Well we can fix this without much work, but using a goto in this way isn't necessarily bad behavior - e.g. the linux kernel uses this convention for doing error handling in only one spot as well and I think the code is quite clear as is.
Using exceptions to fix this is obviously one solution, but this does cost performance in the error case, so I assume that's out of the question.
So if you want to, this should be fine:
你不只是使用 goto。您正在使用进入另一个范围的 goto。更简单:
更干净,没有重复代码,并且可扩展:
You are not just using a goto. You are using a goto that goes into another scope. Much simpler:
Cleaner, no code duplication, and scalable: