Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

IBAlloc #1108

Closed
gsbelarus opened this issue Jun 30, 2015 · 1 comment
Closed

IBAlloc #1108

gsbelarus opened this issue Jun 30, 2015 · 1 comment

Comments

@gsbelarus
Copy link
Member

Originally reported on Google Code with ID 1108

Вместо такого кода:
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

@gsbelarus
Copy link
Member Author

Правильнее не будет. Оба кода правильные. А вот быстрее будет, при условии что 
выделяемые блоки > 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.


Reported by gs1994 on 2008-10-31 12:08:14

  • Status changed: Fixed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant