According to this presentation (http://oud.ocaml.org/2012/slides/oud2012-paper13-slides.pdf, PDF page 4), the following two data structures use different amount of memory
type t1 = { f1: float; f2:float};;
type t2 = (float * float);;
And t1 use less memory than t2, can anybody explain to me why is this the case?
19.3.3 of http://caml.inria.fr/pub/docs/manual-ocaml/intfc.html#sec425 says:
Arrays of floating-point numbers (type float array) have a special, unboxed, more efficient representation. These arrays are represented by pointers to blocks with tag
Double_array_tag
.
This is introduced to handle big float arrays efficiently, but this applies also to record types only with floats.
https://realworldocaml.org/v1/en/html/memory-representation-of-values.html is also a very good documentation which explains the internal value representation of OCaml.
In addition to camlspotter answer a few clarification notes:
float
s are exceptions. By default, each float is boxed, i.e., represented not as immediate value, but as a pointer to the allocated double precision floating point value. OCaml optimizes float records and arrays to store data directly, without double boxing. float ref
, that is underneath the hood is a record of type a ref = {mutable contents : 'a}
still occupies extra amount of space, i.e., it is a pointer to a record, that contains a pointer to the word. But, if you define, type float_ref = {mutable float_contents : float}
this would be a pointer to a record that contains directly a float value. If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With