Why does Shortstring consume more memory than an ordinary String?

Asked

Viewed 115 times

3

I made an example here to see how much memory consumes each variable and noticed that a variable of type ShortString consumes 256 while a variable of type String consumes only 4. Following 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.

1 answer

6


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. It has a total size of 2 to 256 bytes, one byte is used to indicate its size. The size can not change neither for more nor for less. Example of use:

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

I put in the Github for future reference.

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

  • It is therefore recommended not to use shortstrings?

  • Exactly, as it is in the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.