将函数结果与多个值进行比较

Compare Function result to multiple values

我正在重新设计我的一些 For 循环以 运行 更快。特别是那些调用函数来比较值的函数。我想知道我的基础 Delphi 知识是否缺少一些真正有用的东西。

我有很多类似这样的 For 循环:

for i :=1 to 10000 do
  begin
    //---  Check if Condition for each Object (i) Property = Yes, Y or a Number  --- 
    if (fGetPropValue(i,'Condition')='Yes') Or (fGetPropValue(i,'Condition')='Y') Or (StrToIntDef(fGetPropValue(i,'Condition'),0)>0)
    then
      // code...

  end;

在这种情况下,如果结果不同于 Yes 或 Y,函数将被调用 3 次。如果结果为 Yes,则只调用一次并跳过其余调用。

我可以使用单次调用并将值存储到变量,如下所示:

for i :=1 to 10000 do
begin
  //---  Get Condition for each Object (i) Property   ---
  vCondition:=fGetPropValue(i,'Condition');
  //---  Check Condition = Yes, Y or a number  ---
  if (vCondition='Yes') Or (vCondition='Y') Or (StrtoIntDef(vCondition,0)>0)
  then
    // code...

end;

这很好,但是如果我需要比较更复杂的情况,比如:

for i :=1 to 10000 do
  begin

    if (fGetPropValue(i,'Condition')='Yes') Or (fGetPropValue(i,'Condition')='Y') Or (StrtoIntDef(fGetPropValue(i,'Condition'),0)>0) And
       (fGetPropValue(i,'Enabled')='Yes') Or (fGetPropValue(i,'Enabled')='Y') Or (StrtoIntDef(fGetPropValue(i,'Enabled'),0)>0) And
       (fGetPropValue(i,'Visible')='Yes') Or (fGetPropValue(i,'Visible')='Y') Or (StrtoIntDef(fGetPropValue(i,'Visible'),0)>0) And
       (fGetPropValue(i,'AllowAccess')='Yes') Or (fGetPropValue(i,'AllowAccess')='Y') Or (StrtoIntDef(fGetPropValue(i,'AllowAccess'),0)>0)
    then
      // code...

  end;

在这种情况下,如果我引入 4 个变量并获取所有 4 个值,如果第一个逻辑比较为真,我将消除 speedy 选项 - 没有 4 个变量它将不再执行调用。

有什么方法可以重新设计复杂比较?

您需要将其提取到可以重复使用的函数中:

function PropValueIsTrue(const PropValue: string): Boolean;
begin
  Result := (PropValue='Yes') or (PropValue='Y') or (StrtoIntDef(PropValue,0)>0);
end;

那么你的代码就变成了:

if PropValueIsTrue(fGetPropValue(i,'Condition')) and
   PropValueIsTrue(fGetPropValue(i,'Enabled')) and
   PropValueIsTrue(fGetPropValue(i,'Visible')) and
   PropValueIsTrue(fGetPropValue(i,'AllowAccess')) then