#1 2021-08-08 16:49:48

okoba
Member
Registered: 2019-09-29
Posts: 106

Fast compare string

I noticed that when I include mormot.core.data, it makes comparing string (A=B) fast. Checking that subject I found that mormot.core.rtti patches the fpc_ansistr_compare and it is very fast, excellent.
The question for me is that why mORMot do not use this functions for other parts (eg DynArray) and uses StrComp instead?

   procedure Test;
  var
    I, C: Int64;
    A, B: String;
    T: TLocalPrecisionTimer;
  begin
    A := 'Hello World';
    UniqueString(A);
    B := 'Hello World';
    UniqueString(B);
    C := 0;
    T := TLocalPrecisionTimer.CreateAndStart;
    for I := 1 to 50 * 1000 * 1000 do
      if A = B then //_ansistr_compare_equal //95ms
        //if SortDynArrayString(A, B) = 0 then
        //if StrComp(PChar(A), PChar(B)) = 0 then //367ms
        C += 1;
    Writeln(C, ' ', T.Stop);
  end;
                        

Offline

#2 2021-08-08 20:05:04

ab
Administrator
From: France
Registered: 2010-06-21
Posts: 14,182
Website

Re: Fast compare string

_ansistr_compare_equal is for equality only, it does not support < or > comparison, which is needed by TDynArray.

In fact, if you check the code, SortDynArrayString() is never called by TDynArray.
The mORMot code will select automatically SortDynArrayAnsiString(const A, B) which is very optimized, and written in hand tuned ASM for both i386 and x86_64. It compares the first char ASAP to enhance sort, and can compare one pointer size (4 or 8 bytes) at a time in its internal loop. See PT_SORT[] in mormot.core.data.

Offline

#3 2021-08-09 08:33:30

okoba
Member
Registered: 2019-09-29
Posts: 106

Re: Fast compare string

Thank you for the clarification. Interesting as always.

Offline

Board footer

Powered by FluxBB