On Wednesday, 11 October 2023 at 03:15:30 UTC, H. S. Teoh wrote:
On Wed, Oct 11, 2023 at 02:54:53AM +0000, mw via Digitalmars-d-learn wrote:
Hi,

I want to confirm: in the following loop, is the array literal `a` vs. `b` stack or heap allocated? and how many times?

void main() {

int[2] a;

This is stack-allocated. Once per call to the function.


int[] b;

This is an empty slice. It can refer to either stack or heap memory, depending on what's assigned to it.


int i;
While(++i <=100) {

  a = [i, i+1];  // array literal

`a` is overwritten in-place once per loop.

How about the temporary array literal on the right hand side? It's stack / heap allocated? Or it's not in the language specification, but up to the (optimizing) compiler to decide?


  b = [i, i+1];
[...]

A new array consisting of 2 elements is allocated, once per loop, and assigned to b each time. Any arrays from previous iterations will be collected by the GC eventually.


T


Reply via email to