Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does copy and update for immutable record types in F# share or copy memory?

Does the copy and update procedure for immutable records in F# share or copy memory? Meaning, in the following code

type MyRecord = {
    X: int;
    Y: int;
    Z: int 
    }

let myRecord1 = { X = 1; Y = 2; Z = 3; }
let myRecord2 = { myRecord1 with Y = 100; Z = 2 }

do myRecord1 and myRecord2 share memory for the variable X? More generally, is there a good reference that denotes exactly which immutable/persistent data structures in F# actively share memory?

like image 342
wyer33 Avatar asked Mar 27 '15 03:03

wyer33


1 Answers

In this case, the memory for variable X will be copied. The last line of your code is really just another way of writing this:

let myRecord2 = { X = myRecord1.X; Y = 100; Z = 2 }

Now, if X was of a reference type, the memory for reference to it would have been copied, but the memory for its contents would have been shared.

For example, consider this:

type MyX = { W: int; U: int }
type MyRecord = {
    X: MyX;
    Y: int;
    Z: int 
    }

let myRecord1 = { X =  { W = 5; U = 6 }; Y = 2; Z = 3; }
let myRecord2 = { myRecord1 with Y = 100; Z = 2 }

In the above code, the memory for X will be copied, but memory for W and U will be shared.

like image 134
Fyodor Soikin Avatar answered Oct 13 '22 00:10

Fyodor Soikin