Version française
Home     About     Download     Resources     Contact us    
Browse thread
mixed functional / object style
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Jacques Garrigue <garrigue@m...>
Subject: Re: [Caml-list] mixed functional / object style
From: Guillaume Hennequin <gje.hennequin@gmail.com>
> Dear list,
> 
> this is a somewhat naive question
> let's define
> 
> class a = object
>  val mutable v = ...
>  method v = v
>  method m = something that uses v
> end ;;
> 
> now assume that I want to create a lot of those a objects, so many that I
> may encounter memory problems.
> 
> I thought the following would be better, memory wise, but when I test it
> doesn't seem to be the case
> 
> class a = object
>  val mutable v = ...
>  method v = v
> end ;;
> 
> and instead of each object having its own method m, I define it separately
> let m x = something that calls x#v
> 
> This question is somewhat equivalent to: what is the memory consumption of a
> simple method
> method m = let _ = self#v in () ??

A better answer is that objects have a two-level structure.
They are represented by a record containing their fields, an object id
(use for comparison) and a pointer to a shared method table (share by
all objects generate from the same class).
So adding a method to a class does not change the memory consumption
for generated objects.

However, beware that the number of fields in an object is not only the
number of val in its class definition. Constructor arguments or
intermediate values generated by let statements are automatically
converted into implicit fields if they are used by methods or
initializers.

class c x y z =
  let t = y + z in
  object
    method x = x
    method t = t
  end
The above class has just two implicit fields, x and t.

Jacques Garrigue