wyer33
wyer33

Reputation: 6350

How much memory is shared during an immutable record or object update in OCaml?

How much memory is shared between objects during an immutable record or object update in OCaml? For example, for the records in the code:

type foo = {
    a : int;
    b : int;
    c : int}

let f1 = {a = 1; b=2; c=3}
let f2 = {f1 with c=4}

How much memory is shared between f1 and f2? Basically, do they share memory for a and b? Similarly, for the objects in the code:

type ('i, 'j) lens = { get : 'j; set : 'j -> 'i }
class bar = object
    val a = 1
    method a = {
        get = a;
        set = fun a' -> {< a = a' >}
    }
    val b = 2
    method b = {
        get = b;
        set = fun b' -> {< b = b' >}
    }
    val c = 3
    method c = {
        get = c;
        set = fun c' -> {< c = c' >}
    }
end
let b1 = new bar
let b2 = b1#c.set 4

How much memory is shared between b1 and b2?

Basically, imagine a situation where the fields a, b, and c are really, really big. I'd like to do an immutable update, but I don't want to have to copy all of that memory if possible.

Upvotes: 2

Views: 189

Answers (1)

Thomash
Thomash

Reputation: 6379

For records, there would be no shared memory between f1 and f2 since an int takes as much memory as a pointer. There would be shared memory if you had more complex objects instead of int. For example in

type foo = {
  a : int list;
  b : int list;
  c : int list;
}

let f1 = {a = [1; 1; 1]; b = [2; 2; 2]; c = [3]}
let f2 = {f1 with c = [4]}

the lists of 1s and 2s would be shared between the two records.

It is a general rule in Ocaml that simple types (int, char, bool, …) are copied but complex types ('a list, 'a array, …) are shared. This is why immutable data structures are good: you can easily share. But beware, data is shared even if it is mutable:

type foo = {x : int ref; y : int ref}
let a = {x=ref 0; y = ref 0}
let b = {a with y = ref 1}
let () = b.x := 2

then a.x equals 2.

Upvotes: 6

Related Questions