delphi - 如何缓存函数 bool 结果

标签 delphi optimization delphi-7

我有这个功能:

var
  _WordApplicationExistsCache: Integer = -1; // Cache result

function WordApplicationExists: Boolean;
var
  WordObj: OleVariant;
begin
  if (_WordApplicationExistsCache = -1) then
  begin
    Result := False;
    try
      try
        WordObj := CreateOleObject('Word.Application');
        WordObj.Visible := False;
        WordObj.Quit;
        WordObj := Unassigned;
        Result := True;
      except
        // error
      end;
    finally
      _WordApplicationExistsCache := Ord(Result); // 0;1
    end;
  end
  else
  begin
    Result := Boolean(_WordApplicationExistsCache);
  end;
end;

我尝试在应用程序生命周期中仅调用此函数一次。我可能根本不会调用这个函数。

这是正确的模式吗?这可以做得更好吗?

编辑: 我能想到的另一种方法是使用 2 个变量:

var
  _WordApplicationExistsInitialized: Boolean = False; // Cache result
  _WordApplicationExistsCacheResult: Boolean; // Undefined ?

function WordApplicationExists: Boolean;
var
  WordObj: OleVariant;
begin
  if not _WordApplicationExistsInitialized then
  begin
    _WordApplicationExistsInitialized := True;
    Result := False;
    try
      try
        WordObj := CreateOleObject('Word.Application');
        WordObj.Visible := False;
        WordObj.Quit;
        WordObj := Unassigned;
        Result := True;
      except
        // error
      end;
    finally
      _WordApplicationExistsCacheResult := Result;
    end;
  end
  else
  begin
    Result := _WordApplicationExistsCacheResult;
  end;
end;

第一个版本让我有点烦恼的是类型转换Boolean<->Integer。如果 Boolean 可以初始化为 nil,那就完美了(我认为)。

最佳答案

对缓存结果使用 TriState 类型。

type
  TTriState = ( tsUnknown, tsFalse, tsTrue );

var
  _WordApplicationExists : TTriState = tsUnknown;

function WordApplicationExists : Boolean;
var
  WordObj: OleVariant;
begin
  if _WordApplicationExists = tsUnknown 
  then
    try
      WordObj := CreateOleObject('Word.Application');
      WordObj.Visible := False;
      WordObj.Quit;
      WordObj := Unassigned;
      _WordApplicationExists := tsTrue;
    except
      _WordApplicationExists := tsFalse;
    end;

  Result := _WordApplicationExists = tsTrue;
end;

关于delphi - 如何缓存函数 bool 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34115762/

相关文章:

delphi - 如何访问 FastMM4 的 RegisterExpectedMemoryLeak?

delphi - 如何根据其父进程创建子进程?

delphi - 在 Delphi 中的远程系统上执行 Postgres 查询时获取本地系统路径

c++ - 如何使用 WM_* 消息调整窗口大小

arrays - 优化从 openCV mat 到 2D float 数组的复制

c - gcc优化的解释

performance - 优化重复的 matlab 代码

Delphi:FireDac 连接阻塞应用程序

delphi - 在 Delphi XE 中渲染混合矢量和位图图像的最佳方法是什么

delphi - 未声明的标识符,不使用谷歌查找单元