我實現語言翻譯應用程序中通過將所有字符串運行時在TStringList中有:如何更快搜索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;
然後我得到使用翻譯:
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;
反正這種方法需要大約30微秒找到一條記錄,是否有更好的方法來實現相同的結果?
UPDATE:以供將來參考我寫在這裏使用TDictionary所建議的新的實現(可與德爾福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;
新GetTranslation函數執行快1000倍(在我的2000樣本記錄),然後是第一個版本。
雖然IndexOf受益於正在排序的TStringList,但IndexOfName卻沒有。這並不是說它*在一些後代類中不能*,但TStringList不會覆蓋TStrings提供的基本線性搜索。 – 2010-09-15 01:16:47
是的,我檢查過,它是相同的(所以我可以節省時間不排序列表。因爲我沒有修改它,它會更有意義的調用排序,而不是設置排序真(無論如何,我不會這樣做) 。謝謝。 – LaBracca 2010-09-15 09:57:48