What's the point of static arrays ?

wjoe invalid at example.com
Fri Jul 10 10:25:32 UTC 2020


On Thursday, 9 July 2020 at 17:15:26 UTC, Jonathan M Davis wrote:
> On Thursday, July 9, 2020 10:21:41 AM MDT H. S. Teoh via 
> Digitalmars-d-learn wrote:
>> > - Assignment copies the whole array, as in int[5] a; auto b 
>> > = a;
>>
>> Sometimes this is desirable.  Consider the 3D game example.  
>> Suppose you're given a vector and need to perform some 
>> computation on it. If it were a dynamic array, you'd need to 
>> allocate a new array on the heap in order to work on it 
>> without changing the original vector. With a static array, 
>> it's passed by value to your function, so you just do what you 
>> need to do with it, and when you're done, either discard it 
>> (== no work because it's allocated on the stack) or return it 
>> (== return on the stack, no allocations).
>
> I recall that at one point, I wrote brute-force sudoku solver, 
> and initially, I'd used dynamic arrays to represent the board. 
> When I switched them to static arrays, it was _way_ faster - 
> presumably, because all of those heap allocations were gone. 
> And of course, since the sudoku board is always the same size, 
> the ability to resize the array was unnecessary.
>
> In most programs that I've written, it hasn't made sense to use 
> static arrays anywhere, but sometimes, they're exactly what you 
> need.
>
> - Jonathan M Davis

Even though dynamic arrays can be resized, they don't need to be 
if the need doesn't arise  - did you measure performance with 
pre-allocated dynamic arrays and disabled bounds checks, too ?

I wouldn't expect that big of a performance difference in that 
scenario, but what you expect and what you get can be vastly 
different. I'm really curious to know.


More information about the Digitalmars-d-learn mailing list