在 OCaml 中的不可变记录或对象更新期间共享多少内存?
How much memory is shared during an immutable record or object update in OCaml?
在 OCaml 中的不可变记录或对象更新期间,对象之间共享多少内存?比如对于代码中的记录:
type foo = {
a : int;
b : int;
c : int}
let f1 = {a = 1; b=2; c=3}
let f2 = {f1 with c=4}
f1
和 f2
共享多少内存?基本上,他们是否共享 a
和 b
的内存?同样,对于代码中的对象:
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
b1
和 b2
共享多少内存?
基本上,想象一下字段 a
、b
和 c
非常非常大的情况。我想进行不可变更新,但我不想尽可能复制所有内存。
对于记录,f1
和 f2
之间没有共享内存,因为 int
占用的内存与指针一样多。如果你有更复杂的对象而不是 int
,就会有共享内存。
例如在
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]}
1 和 2 的列表将在两条记录之间共享。
Ocaml 中的一般规则是简单类型(int
、char
、bool
、...)被复制,而复杂类型('a list
、'a array
, …) 是共享的。这就是不可变数据结构好的原因:您可以轻松共享。但要注意,即使数据是可变的,数据也会被共享:
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
那么 a.x
等于 2
.
在 OCaml 中的不可变记录或对象更新期间,对象之间共享多少内存?比如对于代码中的记录:
type foo = {
a : int;
b : int;
c : int}
let f1 = {a = 1; b=2; c=3}
let f2 = {f1 with c=4}
f1
和 f2
共享多少内存?基本上,他们是否共享 a
和 b
的内存?同样,对于代码中的对象:
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
b1
和 b2
共享多少内存?
基本上,想象一下字段 a
、b
和 c
非常非常大的情况。我想进行不可变更新,但我不想尽可能复制所有内存。
对于记录,f1
和 f2
之间没有共享内存,因为 int
占用的内存与指针一样多。如果你有更复杂的对象而不是 int
,就会有共享内存。
例如在
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]}
1 和 2 的列表将在两条记录之间共享。
Ocaml 中的一般规则是简单类型(int
、char
、bool
、...)被复制,而复杂类型('a list
、'a array
, …) 是共享的。这就是不可变数据结构好的原因:您可以轻松共享。但要注意,即使数据是可变的,数据也会被共享:
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
那么 a.x
等于 2
.