Here is a small poll to help me decide in which direction to go about dynamic arrays in DWScript. The poll is at the bottom of the post, to encourage reading before voting 😉
In Delphi, fixed-size arrays behave as value types, while dynamic arrays behave as reference type, this can be illustrated by:
type TFixedSizeArray = array [0..9] of Integer; TDynamicArray = array of Integer; ... procedure SomeProc(fixed : TFixedSizeArray; dynamic : TDynamicArray); begin fixed:=2; dynamic:=2; end; ... var f : TFixedSizeArray; d : TDynamicArray; begin f:=1; SetLength(d, 10); d:=1; SomeProc(fixed, dynamic); // at this point f is still 1, but d is now 2 end;
However if you change SomeProc to
procedure SomeProc(fixed : TFixedSizeArray; dynamic : TDynamicArray); begin fixed:=2; SetLength(dynamic, 20); dynamic:=2; end;
then d will be unchanged, as the SetLength() call will have spawned a different dynamic array, if you want to resize a dynamic array you have to pass it as a var parameter, while if you only want to change the items, you don’t…
With current Delphi syntax, dynamic arrays are schizophrenic: they are passed by reference, like a TObject would be, but resized as value types.
In a way, dynamic arrays borrow the String type’s SetLength() syntax and behavior, but String is passed in a form that mimics a value type, in the example above, it would behave like TFixedSizeArray, ie. if you modify a String that wasn’t passed as var in SomeProc(), the original variable won’t be changed.
To rationalize the situation, there are two options:
- make dynamic arrays a value type, with similar copy-on-write optimization as String to minimize unnecessary copies. A side benefit is that it makes dynamic arrays behave similarly to fixed-size arrays, all would behave as value types, a downside is a performance hit on write accesses (for the copy-on-write mechanism).
- make SetLength() treat dynamic arrays as a 1st-class reference type, ie. have it work as dynamic.SetLength() would, and if you need to make a unique copy of a dynamic array, you would use a dedicated function like Copy() rather than piggyback SetLength().
So, what would feel more natural to you?
Dynamic arrays would be better as...
- a value type, like non-dynamic arrays, minimize the surprise factor (38%, 22 Votes)
- a full self-respecting reference type, more practical and efficient (62%, 36 Votes)
Total Voters: 58