0

I read a lot of articles and documentation, but still can not completely understand where different data types are stored in memory.

Can you explaing me where in memory mutable String or any another mutable type e.g. var string: String is stored.

And where immutable String or any another immutable type e.g. let string: String is stored?

Can you answer please for both Swift and Objective-C?

trincot
  • 317,000
  • 35
  • 244
  • 286
  • 2
    Why does it matter? In Obj-C they can be stored in static memory (neither stack or heap) if we are talking about literals. Swift will be similar. Most of the times heap will be used. Stack is probably possible but only as an optimization for immutable strings. In Swift the actual String instance can be placed on stack but it will still reference heap. You don't know how complicated answer you want. – Sulthan Jun 14 '17 at 16:24
  • You may wanted to do little googling first: https://stackoverflow.com/questions/27441456/swift-stack-heap-understanding – Dominik Bucher Jun 14 '17 at 16:41
  • Dominik, I had read that answer, but it's very common answer like value types are stored in stack and reference types are stored in heap (but as I understood it's not completely true). – Igor Zhukov Jun 15 '17 at 09:36
  • Sulthan, I want the most complicated answer, I want to dig inside it. I need to understand this conceptions because of 2nd interview stage with CTO (and it's even not for Junior but for Trainee position). – Igor Zhukov Jun 15 '17 at 09:39

1 Answers1

0

Compilers especially in low level languages need to know types and sizes before compiling, types with unknown sizes are stored as mutable on heaps eg:

var = String::from(" String_name ")

This string type can be mutated, whereas for var = " String_name"—which is of str type—cannot be mutated. It is therefore stored on the stack and can be accessed quickly unlike the one stored on heap.

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
N0R4H
  • 1
  • I doubt that all immutable strings are stored on the stack. A lot of them should come from the code segment. – Thilo Jun 28 '20 at 06:22