问题描述
在 Javascript 中,如果我执行以下命令:
if (cond1 && cond2) {
}
如果 cond1 为假,解析器将停止,无需检查 cond2。这对性能有好处。
以同样的方式:
if (cond1 || cond2) {
}
如果 cond1 为真,则无需检查 cond2。
在较新的 Delphi 版本上是否有类似的东西?我在 10.4
谢谢
解决方法
是的,Delphi 编译器支持 boolean short-circuit evaluation。可以使用 compiler directive 启用或禁用它,但默认情况下启用它,并且通常 Delphi 代码假定启用它。
这不仅经常用于提高性能,而且用于更简洁地编写代码。
例如,我经常写这样的东西
if Assigned(X) and X.Enabled then
X.DoSomething;
或
if (delta > 0) and ((b - a)/delta > 1000) then
raise Exception.Create('Too many steps.');
或
if TryStrToInt(s,i) and InRange(i,Low(arr),High(arr)) and (arr[i] = 123) then
DoSomething
或
i := 1;
while (i <= s.Length) and IsWhitespace(s[i]) do
begin
// ...
Inc(i);
end;
或
ValidInput := TryStrToInt(s,i) and (i > 18) and (100 / i > 2)
在所有这些例子中,我依靠评估来“过早地”停止。否则,我会遇到访问冲突、除以零错误、随机行为等问题。
事实上,我每天编写的代码都假设布尔短路评估已开启!
这是惯用的 Delphi。