Como posso pesquisar mais rapidamente pares de nome / valor em um Delphi TStringList?
Implementei a tradução de idiomas em um aplicativo colocando todas as strings em tempo de execução em um TStringList com:
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;
Então eu recebo a tradução usando:
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;
De qualquer forma, com essa abordagem, são necessários cerca de 30 microssegundos para localizar um registro. Existe uma maneira melhor de obter o mesmo resultado?
ATUALIZAÇÃO: Para referência futura, escrevo aqui a nova implementação que usa o TDictionary como sugerido (funciona com o Delphi 2009 e mais recente):
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;
A nova função GetTranslation executa 1000 vezes mais rápido (nos meus registros de amostra de 2000) que a primeira versão.