How can I search faster for name/value pairs in a Delphi TStringList?

前端 未结 5 1568

I implemented language translation in an application by putting all strings at runtime in a TStringList with:

procedure PopulateStringList;
begin  
  EnglishStri         


        
5条回答
  •  醉话见心
    2021-02-04 18:51

    You can also use a CLASS HELPER to re-program the "IndexOfName" function:

    TYPE
      TStringsHelper = CLASS HELPER FOR TStrings
                         FUNCTION IndexOfName(CONST Name : STRING) : INTEGER;
                       END;
    
    FUNCTION TStringsHelper.IndexOfName(CONST Name : STRING) : INTEGER;
      VAR
        SL  : TStringList ABSOLUTE Self;
        S,T : STRING;
        I   : INTEGER;
    
      BEGIN
        IF (Self IS TStringList) AND SL.Sorted THEN BEGIN
          S:=Name+NameValueSeparator;
          IF SL.Find(S,I) THEN
            Result:=I
          ELSE IF (I<0) OR (I>=Count) THEN
            Result:=-1
          ELSE BEGIN
            T:=SL[I];
            IF CompareStrings(COPY(T,1,LENGTH(S)),S)=0 THEN Result:=I ELSE Result:=-1
          END;
          EXIT
        END;
        Result:=INHERITED IndexOfName(Name)
      END;
    

    (or implement it in a descendant TStrings class if you dislike CLASS HELPERs or don't have them in your Delphi version).

    This will use a binary search on a sorted TStringList and a sequential search on other TStrings classes.

提交回复
热议问题