Class instance memory overhead lower than 3 words?

Nicholas Wilson iamthewilsonator at hotmail.com
Thu Jan 25 00:16:27 UTC 2018


On Wednesday, 24 January 2018 at 22:27:40 UTC, Nordlöw wrote:
> On Wednesday, 24 January 2018 at 21:47:26 UTC, H. S. Teoh wrote:
>> On Wed, Jan 24, 2018 at 09:48:21PM +0000, Nordlöw via 
>> Digitalmars-d-learn wrote:
>>> Why is the memory overhead for a class instance as high as 3 
>>> words (24 bytes on 64-bit systems? I find that annoyingly 
>>> much for my knowledge database application.
>> [...]
>>
>> There's been an attempt to get rid of the Monitor field, which 
>> takes up one word, but it didn't seem to have gone anywhere 
>> the last time it was discussed.  I believe originally it was 
>> always initialized, but lately it seems to have been changed 
>> to be lazily initialized, so at least you'll only incur the 
>> computational cost if you actually use it. Nevertheless, the 
>> field itself is still there.
>>
>>
>> T
>
> Can I use `*(cast(size_t*)&c.__monitor)` for storing my own 
> stuff in a class instance `c` if I never use monitors? :)

Maybe, the runtime when destroying that class might think the 
monitor is set and try and destroy the mutex it thinks is where 
the pointer points to.

> BTW: the documentation on the concept of monitors is kind of 
> sparse here
>
> https://dlang.org/spec/class.html#class_properties
>
> What is the `__monitor` property used for? Something with 
> synchronized member functions?

It is used for
```
MyClass mc;
synchronized(mc) // <-
{
     ...
}
```
and I believe synchronized member functions and member functions 
of `synchronized class` (which are the same thing really).

The __monitor field points to a mutex object which is managed by 
the runtime.


More information about the Digitalmars-d-learn mailing list