Local static class fields

Bert Bert at gmail.com
Wed Aug 14 07:38:09 UTC 2019


On Tuesday, 13 August 2019 at 00:17:13 UTC, DanielG wrote:
> On Monday, 12 August 2019 at 22:48:43 UTC, Bert wrote:
>> I have a recursive class structure(think of a graph or tree) 
>> and I need to keep a global state for it,
>
> If I'm understanding the problem correctly, it seems like you 
> have a choice to make: either "bloat" the child nodes by the 
> size of a pointer/reference to the shared tree state (4 or 8 
> bytes), or forego that by traversing the tree (from child to 
> root node) every time you want to access the state.
>

Yes. It's the typical size/speed issue, if, for example, one 
could somehow use pointer manipulation.

If, say, all the nodes could be allocated using special pointer 
where the first node could be calculated then it would solve both 
problems optimally(e.g., ptr & 0xFFFF0000/class_size). Of course 
this is someone rediculous. In my use case the tree is fixed but 
it might not always be.

I was just curious if there was some trick or if's impossible to 
really make it happen.


> But if you don't want traversal every time, you're going to 
> have to cache some kind of pointer (or Tree ID in the case of a 
> central dictionary). I suppose if you got down to the 
> nitty-gritty maybe you could use an 8- or 16-bit value for the 
> key ID? (Disclosure: I know absolutely zero about how D lays 
> out classes and structs in memory, this might not save any 
> memory at all)
>

I guess I could wrap some nodes that contain a pointer to the 
data equally spaced throughout the hierarchy and that will reduce 
overhead.

E.g., The kNth node has a pointer to the state.

This reduces the wasted memory by kN and limits the traversal 
depth to a max of kN.
This might be the easiest method that provides the best of both 
words.

Just inherit from Node and cast to check if it contains the info.


> It would help if you could provide some rough metrics:
>
> - How deep you expect each recursive structure to be (from root 
> to deepest leaf node)
>
> - How many total nodes you expect to have across all trees 
> (such that adding a single pointer to each instance would be 
> memory-prohibitive)
>
> - How often each node will have to access the shared state 
> (such that traversal-every-time would be too slow)
>
> That might help in figuring out the best approach.

These are all unknown, it is a general solution. Obviously since 
these are tree's the depth isn't going to be astronomical but 
they could be quite deep since arrays are technically tree's.


More information about the Digitalmars-d-learn mailing list