关于Delphi上的比较运算符
在 Javascript 中,如果我执行以下命令:
if (cond1 && cond2) {
}
如果 cond1 为假,解析器将停止,无需检查 cond2。这对性能有好处。
以相同的方式 :
if (cond1 || cond2) {
}
如果 cond1 为真,则无需检查 cond2。
在较新的 Delphi 版本上有类似的东西吗?我在 10.4
谢谢
回答
是的,Delphi 编译器支持布尔短路评估。可以使用编译器指令启用或禁用它,但默认情况下它是启用的,并且通常 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)
在所有这些例子中,我依靠评估来“过早地”停止。否则,我会遇到访问冲突、除以零错误、随机行为等问题。
事实上,我每天编写的代码都假定布尔短路评估已开启!
这是惯用的德尔福。
- Don't remove anything. Dupehammer it. Which I did.