¿Cómo puedo buscar más rápido pares de nombre / valor en una Delphi TStringList?
Implementé la traducción de idiomas en una aplicación poniendo todas las cadenas en tiempo de ejecución en una TStringList con:
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;
Luego obtengo la traducción 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 todos modos, con este enfoque se necesitan unos 30 microsegundos para ubicar un registro, ¿hay una mejor manera de lograr el mismo resultado?
ACTUALIZACIÓN: Para referencia futura, escribo aquí la nueva implementación que usa TDictionary como se sugiere (funciona con Delphi 2009 y más reciente):
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;
La nueva función GetTranslation funciona 1000 veces más rápido (en mis 2000 registros de muestra) que la primera versión.