[fpc-pascal] Stack alias for ARC like memory management?

Ryan Joseph ryan at thealchemistguild.com
Wed Apr 25 10:21:32 CEST 2018



> On Apr 25, 2018, at 12:59 PM, Sven Barth via fpc-pascal <fpc-pascal at lists.freepascal.org> wrote:
> 
> The memory model of classes in Object Pascal is heap based. Changing that is asking for trouble and I for one don't even want to fiddle around with that, because I don't see any real benefit in it (and yes I daily work with C++) that couldn't also be solved with a working ARC system. 
> 

Just for fun here’s that same code from the previous post but with the keyword added. :) It’s really a good example because this is the same thing we do over and over again every day so it’s a perfect candidate for a simple compiler optimization. We save a block of code, not forgetting to call free and 2 pointers from GemMem that wasted CPU and got us closer to a fragmented heap.

It’s minor but it’s saves minor amounts of time and CPU cycles, both of which really add up over the lifetime of a program.

The programer in this case knows with 100% certainty they don’t need 2 pointers from GetMem but Pascal forces us anyways, and then makes us clean up the mess we didn’t need to make in the first place.

PS. I’m aware those 2 functions may actually raise exceptions but pretend they didn’t and this was just common memory management we do every day.

new code:

function TBlowFishCripto.Encrypt(const Value: string): string;
var
  en: TBlowFishEncryptStream; stackalias;
  stream: TStringStream; stackalias;
begin
  if length(Value) = 0 then
  begin
    Result := '';
    Exit;
  end;
  stream := TStringStream.Create('');
  en := TBlowFishEncryptStream.Create(FKey, stream);
  en.Write(Value[1], Length(Value));
  Result := stream.DataString;
end;  

original code:

function TBlowFishCripto.Encrypt(const Value: string): string;
var
  en: TBlowFishEncryptStream;
  stream: TStringStream;
begin
  if length(Value) = 0 then
  begin
    Result := '';
    Exit;
  end;
  try
    stream := TStringStream.Create('');
    en := TBlowFishEncryptStream.Create(FKey, stream);
    en.Write(Value[1], Length(Value));
    Result := stream.DataString;
  finally
    FreeAndNil(en);
    FreeAndNil(stream);
  end;
end;  

Regards,
	Ryan Joseph



More information about the fpc-pascal mailing list