Thema: Delphi pos von hinten

Einzelnen Beitrag anzeigen

Benutzerbild von himitsu
himitsu

Registriert seit: 11. Okt 2003
Ort: Elbflorenz
43.195 Beiträge
 
Delphi 12 Athens
 
#14

AW: pos von hinten

  Alt 3. Nov 2010, 17:32
Zitat:
Delphi-Quellcode:
function String_Reverse(S:String):String;
var
  i: Integer;
begin
  Result:='';
  for i:=Length(S) downto 1 do
    begin
      Result:=Result+Copy(S,i,1);
    end;
end;
Also der Code ist ja extremst grausam und unperformat.
Copy(S,i,1) = S[i] .
Und die Unmasse an String-Concationen ist sehr unperformant.

Delphi-Quellcode:
program Project5;

{$APPTYPE CONSOLE}

uses
  Windows, StrUtils;

function StringReverse_Copy(S: String): String;
var
  i: Integer;
begin
  Result := '';
  for i := Length(S) downto 1 do
    Result := Result + Copy(S, i, 1);
end;

function StringReverse_Char(S: String): String;
var
  i: Integer;
begin
  Result := '';
  for i := Length(S) downto 1 do
    Result := Result + S[i];
end;

function StringReverse_Direct(S: String): String;
var
  L, i: Integer;
begin
  L := Length(S);
  SetLength(Result, L);
  for i := L downto 1 do
    Result[i] := S[L - i + 2];
end;

var
  S, S2: String;
  C: Cardinal;
  i: Integer;

begin
  SetLength(S, 1234567);

  C := GetTickCount;
  for i := 0 to 9 do begin
    S2 := StringReverse_Copy(S);
    S2 := '';
  end;
  WriteLn(GetTickCount - C);

  C := GetTickCount;
  for i := 0 to 9 do begin
    S2 := StringReverse_Char(S);
    S2 := '';
  end;
  WriteLn(GetTickCount - C);

  C := GetTickCount;
  for i := 0 to 9 do begin
    S2 := StringReverse_Direct(S);
    S2 := '';
  end;
  WriteLn(GetTickCount - C);

  C := GetTickCount;
  for i := 0 to 9 do begin
    S2 := ReverseString(S);
    S2 := '';
  end;
  WriteLn(GetTickCount - C);

  ReadLn;
end.
Code:
2047
1296
110
47
Je länger der String, um so grausamer wird die nahezu expotentiell zur Zeichenanzahl steigene Rechenzeit.
Garbage Collector ... Delphianer erzeugen keinen Müll, also brauchen sie auch keinen Müllsucher.
my Delphi wish list : BugReports/FeatureRequests

Geändert von himitsu ( 3. Nov 2010 um 18:07 Uhr)
  Mit Zitat antworten Zitat