关于 Delphi 上的比较运算符
About comparison operators on Delphi
在 Javascript 中,如果我执行以下命令:
if (cond1 && cond2) {
}
如果 cond1 为假,解析器将停止,无需检查 cond2。这对性能有好处。
同理:
if (cond1 || cond2) {
}
如果 cond1 为真,则无需检查 cond2。
较新的 Delphi 版本是否有类似的东西?我在 10.4
谢谢
是的,Delphi 编译器支持 boolean short-circuit evaluation. It can be enabled or disabled using a 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。
在 Javascript 中,如果我执行以下命令:
if (cond1 && cond2) {
}
如果 cond1 为假,解析器将停止,无需检查 cond2。这对性能有好处。
同理:
if (cond1 || cond2) {
}
如果 cond1 为真,则无需检查 cond2。
较新的 Delphi 版本是否有类似的东西?我在 10.4
谢谢
是的,Delphi 编译器支持 boolean short-circuit evaluation. It can be enabled or disabled using a 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。