Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Swift store arrays of structs?

Tags:

swift

Could you explain to a C programmer precisely what happens under the hood when you do something along these lines in Swift:

struct X { var a: Int32; var b: Int32 }
class Y { var a: Int32; var b: Int32 }
var x1 = X[](count: 1000)
let x2 = X[](count: 1000)
var y1 = Y[](count: 1000)
let y2 = Y[](count: 1000)

In particular, exactly what is the memory layout? What is allocated from the stack, and what is allocated from the heap? How many separate memory blocks do we allocate here?

My guess is that something along these lines happens:

  • x1 and x2 are pointers to a contiguous memory block that contains the size of the array (1000), followed by 2000 integers (storing x1[0].a, x1[0].b, x1[1].a, ... in this order); the memory block is allocated from the heap.

  • y1 and y2 are pointers to a contiguous memory block that contains the size of the array (1000), followed by 1000 pointers (storing a reference to objects y1[0], y1[1], ...); each of these points to a separate memory block that represents an instance of object Y, and these memory blocks contain reference counters + fields a and b; each object Y is separately allocated from the heap.

Is this anywhere near to what actually happens in Apple's current implementation of Swift?

In the resulting machine code, is there any difference between how x1 and x2 are stored or accessed? What about between y1 and y2?

like image 610
Jukka Suomela Avatar asked Jun 04 '14 12:06

Jukka Suomela


1 Answers

It is unspecified. You can go and disassemble the compiled code, but that's just what it currently does, and it may change at any time with no notice.

I do understand the desire of a C programmer to try to figure out what happens under the hood. But you really really should not care at all. It's like when C came out and programmers, used to work in assembly, wanted to know exactly at what physical memory address a struct was stored or which local variables were being mapped to CPU registers and which to the stack frame. In very early compilers that was something you could actually know, but you really should not care. Not even if you think it makes a difference.

like image 135
Analog File Avatar answered Nov 10 '22 15:11

Analog File