如何更快地搜索Delphi TStringList中的名称/值对?

LaB*_*cca 6 delphi tstringlist

我通过在运行时将所有字符串放在TStringList中来实现应用程序中的语言转换:

procedure PopulateStringList;
begin  
  EnglishStringList.Append('CAN_T_FIND_FILE=It is not possible to find the file');
  EnglishStringList.Append('DUMMY=Just a dummy record');
  // total of 2000 record appended in the same way
  EnglishStringList.Sorted := True; // Updated comment: this is USELESS!
end;
Run Code Online (Sandbox Code Playgroud)

然后我使用以下方式获得翻译:

function GetTranslation(ResStr:String):String;
var
  iIndex : Integer;
begin
  iIndex := -1;
  iIndex :=  EnglishStringList.IndexOfName(ResStr);
  if iIndex >= 0 then
  Result :=  EnglishStringList.ValueFromIndex[iIndex] else
  Result := ResStr + ' (Translation N/A)';
end;
Run Code Online (Sandbox Code Playgroud)

无论如何使用这种方法找到一条记录需要大约30微秒,是否有更好的方法来实现相同的结果?

更新:为了将来的参考,我在这里写了建议使用TDictionary的新实现(适用于Delphi 2009及更新版本):

procedure PopulateStringList;
begin  
  EnglishDictionary := TDictionary<String, String>.Create;
  EnglishDictionary.Add('CAN_T_FIND_FILE','It is not possible to find the file');
  EnglishDictionary.Add('DUMMY','Just a dummy record');
  // total of 2000 record appended in the same way
end;


function GetTranslation(ResStr:String):String;
var
  ValueFound: Boolean;
begin
  ValueFound:=  EnglishDictionary.TryGetValue(ResStr, Result);
  if not ValueFound then Result := Result + '(Trans N/A)';
end;
Run Code Online (Sandbox Code Playgroud)

新的GetTranslation函数比第一个版本快1000倍(在我的2000个样本记录上).

spl*_*ash 17

THashedStringList 我认为应该会更好.


Vil*_*nde 15

在Delphi 2009或更高版本中,我将在Generics.Collections中使用TDictionary <string,string>.另请注意,有一些免费工具,如http://dxgettext.po.dk/,用于翻译应用程序.

  • 我有Delpgi 2009,我第一次尝试使用泛型,如建议的TDictionary <String,String> ...在我的情况下,它比THashedStringList快40倍.我只使用了TDictionary方法Add和TryGetValue.即使在2009年我也"安全"吗?所以我接受这个作为答案,因为现在我的速度快了1000倍.TStringList到THashedStringList给了x25,THashedStringList到TDictionary <String,String>给了额外的x40.总计x1000. (3认同)

lke*_*ler 13

如果THashedStringList适合你,那很好.它最大的缺点是每次更改列表的内容时,都会重建哈希表.因此,只要您的列表仍然很小或者不经常更改,它就会对您有用.

有关这方面的更多信息,请参阅:THashedStringList弱点,它提供了一些替代方案.

如果您有可能会被更新的大名单,你可能想尝试GpStringHash贾布尔,即不必在每次改变重新计算整个表.