What's the point of static arrays ?

Ali Çehreli acehreli at yahoo.com
Fri Jul 10 21:24:08 UTC 2020

On 7/10/20 8:03 AM, wjoe wrote:

 > What I'm saying is even if this allocation is slow let's say 5ms, but it
 > only happens once, that wouldn't matter to overall performance at all.

Yes, you are correct and there are dynamic arrays that are allocated 
once in many programs.

I haven't read the rest of your post but you've said elsewhere that a 
static array is on the stack. Yes, there are such static arrays but the 
issue is not that simple.

struct S {
   float[3] rgb;  // Can be on the stack or dynamic memory

The member of that struct can be anywhere:

void foo() {
   S s;                // On the stack
   auto arr = [ S() ]; // On dynamically allocated memory

Additionally, as is common and understandable in D, we are conflating 
dynamic arrays and slices. The way I see it is dynamic array is owned by 
the D runtime. Although a slice is an interface to such dynamic arrays, 
a slice can start its life with non-dynamic arrays and may or may not 
move to accessing dynamic arrays.

struct S {
   float[] arr;  // A slice can use dynamic or static memory

void foo() {
   float[10] storage;
   auto a = S(storage[1..7]);  // Slice is referring to the stack space
   auto b = S();
   b.arr ~= 1.5;               // Slice is referring to dynamic memory

What is important is overhead:

1) Allocation: Only sometimes an issue.

2) Cost of the slice object (1 pointer and 1 size_t): The cost of this 
may be enormous. (Compare the 12-byte rgb above to a 16-byte slice 

3) Cost of accessing the elements: The access through that extra level 
of indirection may be a cost but the CPU can alleviate it by 
pre-fetching or caching but only for some access patterns.

4) Bounds checking: Some bounds checks for static arrays can be elided 
at run time.

So, there are cases where a dynamic array is better (or must), there are 
cases there is no winner and there are cases where a static array is a 
huge win.


More information about the Digitalmars-d-learn mailing list