Why Shortstring consumes more memory than a common String

3

I've done an example here to see how much memory consumes each variable and I noticed that a variable of type ShortString consumes 256 while a variable of type String consumes only 4. Here's an example for verification:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs;

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
    String1: ShortString;
    String2: String;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
begin
   String1 := 'Teste';
   String2 := 'Teste';
   ShowMessage(Format('String1: %d'+#13+'String2: %d',[SizeOf(String1),SizeOf(String2)]));
end;

end.
    
asked by anonymous 19.05.2017 / 15:29

1 answer

5

ShortString is a type by value, so the text is in it. String is a type by reference, so the variable will only have a pointer to the text that is elsewhere.

Note that ShortString can be up to 255 characters long. It has the total size of 2 to 256 bytes, one byte is used to indicate the size of it. Size can not change for more, not for less. Example usage:

var texto : string[30]; //ocupará 31 bytes

It is considered obsolete and should not be used, it is difficult to make it work correctly.

19.05.2017 / 15:45