Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the Length() function in Delphi work?

Tags:

arrays

delphi

  • In other languages like C++, you have to keep track of the array length yourself - how does Delphi know the length of my array? Is there an internal, hidden integer?

  • Is it better, for performance-critical parts, to not use Length() but a direct integer managed by me?

like image 892
Nostrovje Avatar asked Oct 21 '10 13:10

Nostrovje


2 Answers

There are three kinds of arrays, and Length works differently for each:

  • Dynamic arrays: These are implemented as pointers. The pointer points to the first array element, but "behind" that element (at a negative offset from the start of the array) are two extra integer values that represent the array's length and reference count. Length reads that value. This is the same as for the string type.

  • Static arrays: The compiler knows the length of the array, so Length is a compile-time constant.

  • Open arrays: The length of an open array parameter is passed as a separate parameter. The compiler knows where to find that parameter, so it replaces Length with that a read of that parameter's value.

like image 185
Rob Kennedy Avatar answered Oct 05 '22 03:10

Rob Kennedy


Don't forget that the layout of dynamic arrays and the like would change in a 64-bit version of Delphi, so any code that relies on finding the length at a particular offset would break.

I advise just using Length(). If you're working with it in a loop, you might want to cache it, but don't forget that a for loop already caches the terminating bounds of the loop.

like image 40
Barry Kelly Avatar answered Oct 05 '22 05:10

Barry Kelly