he implementado traducción de idiomas en una aplicación, poniendo todas las cadenas en tiempo de ejecución en un TStringList con:¿Cómo puedo buscar pares de nombre/valor más rápido en una Delphi 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;
entonces consigo 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 tarda unos 30 microsegundos para ubicar un registro, ¿hay una mejor manera de lograr el mismo resultado?
ACTUALIZACIÓN: Para futuras referencias que escribo aquí la nueva aplicación que utiliza TDictionary como se sugiere (trabaja con Delphi 2009 y posteriores):
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 realiza 1000 veces más rápido (en mi 2000 registros de muestra) luego la primera versión.
Aunque los beneficios de 'IndexOf' de una TStringList se ordenan,' IndexOfName' no. Eso no quiere decir que * no * en alguna clase descendiente, pero TStringList no anula la búsqueda lineal básica que proporciona TStrings. –
Sí, lo he comprobado, es lo mismo (así que puedo ahorrar tiempo sin ordenar la lista. Como no lo estoy modificando, tendría más sentido llamar a Sort, en lugar de configurarlo como True (de todos modos, no lo haré) .Gracias. – LaBracca