You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Вместо такого кода:
procedure IBAlloc(var P; OldSize, NewSize: Integer);
var
i: Integer;
begin
if Assigned(Pointer(P)) then
ReallocMem(Pointer(P), NewSize)
else
GetMem(Pointer(P), NewSize);
for i := OldSize to NewSize - 1 do
PChar(P)[i] := #0;
end;
Лучше написать такой, будет правильнее и быстрее:
procedure IBAlloc(var P; OldSize, NewSize: Integer);
begin
if Assigned(Pointer(P)) then
ReallocMem(Pointer(P), NewSize)
else
GetMem(Pointer(P), NewSize);
if NewSize > OldSize then
FillChar((PChar(P) + OldSize)^, NewSize - OldSize, 0);
end;
Reported by Alexander.GoldenSoft on 2008-10-30 10:31:45
The text was updated successfully, but these errors were encountered:
Правильнее не будет. Оба кода правильные. А вот быстрее будет, при условии что
выделяемые блоки > 1024. На маленькиз блоках разница не столь существенна.
Код, на котором можно потестировать:
unit TestIBAlloc_Unit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure IBAlloc1(var P; OldSize, NewSize: Integer);
var
i: Integer;
begin
if Assigned(Pointer(P)) then
ReallocMem(Pointer(P), NewSize)
else
GetMem(Pointer(P), NewSize);
for i := OldSize to NewSize - 1 do
PChar(P)[i] := #0;
end;
procedure IBAlloc2(var P; OldSize, NewSize: Integer);
begin
if Assigned(Pointer(P)) then
ReallocMem(Pointer(P), NewSize)
else
GetMem(Pointer(P), NewSize);
if NewSize > OldSize then
FillChar(PChar(P)[OldSize], NewSize - OldSize, 0);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
P: PChar;
T: TDateTime;
OldSize, NewSize: Integer;
I: Integer;
begin
OldSize := 0;
P := nil;
T := Now;
for I := 1 to 10000000 do
begin
NewSize := Random(8192);
IBAlloc1(P, OldSize, NewSize);
OldSize := NewSize;
end;
IBAlloc1(P, OldSize, 0);
ShowMessage(FormatDateTime('nn:ss.zzz', Now - T));
end;
end.
Originally reported on Google Code with ID 1108
Reported by
Alexander.GoldenSoft
on 2008-10-30 10:31:45The text was updated successfully, but these errors were encountered: