Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why product use more memory than record?

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?

like image 326
Bob Fang Avatar asked Dec 19 '22 05:12

Bob Fang


2 Answers

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.

like image 57
camlspotter Avatar answered Jan 15 '23 13:01

camlspotter


In addition to camlspotter answer a few clarification notes:

  1. In general records, arrays and tuples use the same amount of memory.
  2. Some compound data structures using floats 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.
  3. This doesn't work for polymorphic records, e.g., 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.
like image 23
ivg Avatar answered Jan 15 '23 13:01

ivg