.dup vs operation on all elements

Jonathan M Davis newsgroup.d at jmdavisprog.com
Mon Dec 3 20:37:22 UTC 2018


On Monday, December 3, 2018 1:07:24 PM MST Goksan via Digitalmars-d-learn 
wrote:
> Are there any differences between these 2 methods of copying
> elements?
>
> double[] array = [ 1, 20, 2, 30, 7, 11 ];
>
> // Non dup
> double[6] bracket_syntax_dup = array;
> bracket_syntax_dup[] = array;
> bracket_syntax_dup[0] = 50;
>
> // Dup
> double[6] normal_dup = array.dup;
> normal_dup[0] = 100;
>
> OUTPUT: (array, bracket_syntax_dup and normal_dup respectively):
> [1, 20, 2, 30, 7, 11]
> [50, 20, 2, 30, 7, 11]
> [100, 20, 2, 30, 7, 11]

dup allocates a new dynamic array and copies the elements of the existing
dynamic array to the new one. Calling dup in order to assign to a static
array is just needlessly allocating a dynamic array. The contents of the
array are going to be copied to the static array regardless, but instead of
just copying the elements, if you use dup, you're allocating a new dynamic
array, copying the elements into that dynamic array, and then you're copying
the elements into the static array. There's no point.

You use dup when you want to copy the elements of a dynamic array instead of
simply slicing it. Slicing gives you a new dynamic array that points to
exactly the same elements. It's just copying the pointer and the length
(meaning that mutating the elements of the new slice will affect the
elements in the original array), whereas dup actually allocates a new block
of memory for the new dynamic array to be a slice of (copying the elements
over in the process), so mutating the elements in the new dynamic array then
won't affect the elements in the original.

Regardless, when you create a static array, it's not a slice of anything
(since its elements sit directly on the stack), and when assign to it,
you're simply copying the elements over.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list