What's the point of static arrays ?

wjoe invalid at example.com
Fri Jul 10 14:20:15 UTC 2020


On Friday, 10 July 2020 at 10:47:49 UTC, psycha0s wrote:
> On Friday, 10 July 2020 at 10:13:23 UTC, wjoe wrote:
>> However stack memory needs to be allocated at program start. I 
>> don't see a huge benefit in allocation speed vs. heap 
>> pre-allocation, or is there?
>> I mean 1 allocation vs 2 isn't going to noticeably improve 
>> overall performance.
>
> Allocation on the stack is basically just a single processor 
> instruction that moves the stack pointer (well, ofc you also 
> need to initialize array elements). Meanwhile, allocation on 
> the heap involves much more complex logic of the memory 
> allocator. Moreover, in D dynamic arrays use GC, thus the 
> memory allocation may involve the trash collection step.

On Friday, 10 July 2020 at 11:20:17 UTC, Simen Kjærås wrote:
> You seem to still be thinking of static arrays as the same kind 
> of "thing" as a dynamic array. They're (usually) more like ints 
> or structs than containers: they're generally small, they're 
> often parts of other structures or classes, and they're fairly 
> often the element type of a larger dynamic array. For instance, 
> a bitmap image could be a byte[4][][], with dynamic dimensions 
> 3840x2160. If instead of byte[4] we used byte[], not only would 
> things grind to a halt immediately, we'd also be using 
> massively more memory.

No, not quite. My idea of the stack is like a pre-allocated 
amount of memory in computer RAM which is pointed to by the stack 
pointer.
And further that at program start,whn the process is created, 
this memory needs to be allocated by the OS, just like any other 
memory allocation in protected mode, but only once for the entire 
run time of the process.
(And since there is an allocation when a process/thread is 
created, the act of creating a thread is considered slow.)
A static array resides in this memory (with a fixed length, so a 
length needn't be stored because bounds can be checked at compile 
time) if declared as a variable and is accessed via stack pointer 
and offset.

As for dynamic arrays, that's an allocated amount 
(length/capacity) of memory in computer RAM which is not part of 
the stack (the heap).
Whichever creation process is chosen (malloc, GC, Pool that 
doesn't allocate but just returns a pointer/length, etc.) you end 
up with a pointer to the allocated memory in computer RAM and a 
length variable.

But when the static array is part of a data structure which 
itself is stored in a dynamic array, this memory is accessed 
through the pointer of the dynamic array.

Is that not correct ?


Thanks for the answers :)


More information about the Digitalmars-d-learn mailing list