Strings - memory usage lazarus / 9-Editor ---------------------------------------------------------------------- LazaruX · 2009-02-27 18:27 Hi, the Pascal language has got the following string types: Code: [Select]var    Str1 : Char;        // Holds a single character, small alphabet    Str2 : WideChar;    // Holds a single character, International alphabet    Str3 : AnsiChar;    // Holds a single character, small alphabet    Str4 : ShortString; // Holds a string of up to 255 Char's    Str5 : String;      // Holds strings of Char's of any size desired    Str6 : AnsiString;  // Holds strings of AnsiChar's any size desired    Str7 : WideString;  // Holds strings of WideChar's of any size desired My question is: does a shortstring consume less memory than a string? My doubt is that a shortstring reservs the space for a 255 charachter string in memory, so even if its of 2 chars, still 255 chars were reserved in memory. But a string can be of any size, so if a string is like this: "thestring" Would it reserve it just the space for 9 chars or for more?? ---------------------------------------------------------------------- Marc · 2009-02-27 19:36 A short string allocates always 256 bytes. You can check this with Code: [Select]WriteLn(SizeOf(ShortString)); An AnsiString allocates at least 8 bytes (reference count + size) + the chars in your string. Further each reference to it holds a pointer. Besides this, when assigning, ShortSting := Shortstring, the contents is copied and you use 512 bytes. For a AnsiString := AnsiString you have your string once, and 2 pointers pointing to it (and a refcount of 2) ---------------------------------------------------------------------- LazaruX · 2009-02-28 21:52 Sooo...(I am not sure I have understood correctly)... If I need a string who's size is not defined in the beginning that uses less memory that is able to store at least 256 charachters (more are not needed) I should use a: ?? shortstring or a string?? ---------------------------------------------------------------------- Marc · 2009-03-01 13:19 AnsiString is uses less memory. Note that I write AnsiString, since depending on the compiler mode, a String is either a ShortString ($mode fpc or objfpc) or AnsiString ($mode objfpc or delphi) edit: corrected objfpc mode ---------------------------------------------------------------------- Vincent Snijders · 2009-03-02 09:01 In $mode objfpc string is shortstring too. That is why the Lazarus unit template doesCode: [Select]{$mode objfpc}{$H+}to enable 'string means ansistring'. ---------------------------------------------------------------------- Marc · 2009-03-02 10:58 You're right, I forgot that we put the $H+ in each unit