Einzelnen Beitrag anzeigen

EgonHugeist

Registriert seit: 17. Sep 2011
187 Beiträge
 
Delphi 10.2 Tokyo Starter
 
#102

AW: Anzahl eines Zeichens im String ermitteln

  Alt 14. Jul 2018, 09:56
Double Post. Hab sind noch zwei:

mit direktem Inc des Boolschen ordinals:
Delphi-Quellcode:
function EH_CharCount_5(const S: string; C: Char): Cardinal;
var
  P, PEnd: PChar;
begin
  Result := 0;
  P := Pointer(S);
  if P = nil then Exit;
  PEnd := P + PStrLenInt(NativeUInt(P) - SizeOf(StrLenInt))^-8;
  while P < PEnd do begin
    //comapre 8 Chars per loop
    //this is a simple technic to reduce the loop.
    Inc(Result, Ord(P^=C));
    Inc(Result, Ord((P+1)^=C));
    Inc(Result, Ord((P+2)^=C));
    Inc(Result, Ord((P+3)^=C));
    Inc(Result, Ord((P+4)^=C));
    Inc(Result, Ord((P+5)^=C));
    Inc(Result, Ord((P+6)^=C));
    Inc(Result, Ord((P+7)^=C));
    Inc(P, 8);
  end;
  Inc(PEnd, 8);
  while P < PEnd do begin
    Inc(Result, Ord(P^=C));
    Inc(P);
  end;
end;
ohne direktem Inc des Boolschen ordinals mit if ? then
Delphi-Quellcode:
function EH_CharCount_6(const S: string; C: Char): Cardinal;
var
  P, PEnd: PChar;
begin
  Result := 0;
  P := Pointer(S);
  if P = nil then Exit;
  PEnd := P + PStrLenInt(NativeUInt(P) - SizeOf(StrLenInt))^-8;
  while P < PEnd do begin
    //comapre 8 Chars per loop
    //this is a simple technic to reduce the loop.
    if P^ = C then Inc(Result);
    if (P+1)^ = C then Inc(Result);
    if (P+2)^ = C then Inc(Result);
    if (P+3)^ = C then Inc(Result);
    if (P+4)^ = C then Inc(Result);
    if (P+5)^ = C then Inc(Result);
    if (P+6)^ = C then Inc(Result);
    if (P+7)^ = C then Inc(Result);
    Inc(P, 8);
  end;
  Inc(PEnd, 8);
  while P < PEnd do begin
    if P^=C then
      Inc(Result);
    Inc(P);
  end;
end;
Dies ist die eine typische Technik um die Loops zu reduzieren. Man kann das noch weiter aufbohren für seeehhhr lange strings.
Bei mir rockt EH_CharCount_5 am schnellsten:
Zitat:
00000 Calibrate
04814 1234588 miep
08272 Ydobon
04056 marabu
05014 Missionar
04429 alzaimar
04238 Uwe Raabe StringCountChar
04067 Uwe Raabe StringCountCharFor
04029 KodeZwerg CountCharInString
10193 KodeZwerg CharInStringA
04606 Neutral General CharCountAsm
04501 Uwe Raabe CharCount
04016 Egon Hugeist CharCount_1
04490 Egon Hugeist CharCount_2
04541 Egon Hugeist CharCount_Double_Sided_3
03771 Egon Hugeist CharCount_Double_Sided_4
03199 Egon Hugeist CharCount_5
03803 Egon Hugeist CharCount_6
04657 Delphi CountChar
Compilat hängt an zum Vergleich.
Angehängte Dateien
Dateityp: zip CountCharBenchmark.zip (881,7 KB, 6x aufgerufen)

Geändert von EgonHugeist (14. Jul 2018 um 09:58 Uhr) Grund: Exe hochgeladen
  Mit Zitat antworten Zitat