I got a little question which might be obvious for long-term devs, but I’m still unsure. And because so many of those explanation stuff in the web is LLM-generated these days, I would prefer replies from some of you experienced (Zig)devs ![]()
The scenario: I have a larger main data structure which holds a hash map of smaller substructs with key a u32 id and value a single substruct item (e.g. as kind of cache). Now, one of those cached substructs is always kind of “active”, because its the main source for the ongoing internal operations and thus should be stored in a field of the main structure. Because the active substructure item could be edited, it can’t be const; plus the cache needs to get those updates too, because the program is a long-running process and the active item can change several times (and also back to former already active items).
Now the main question to me is: is it preferable to store this active substruct as pointer into the hash map or as dereferenced item of the pointer into the hash map.
Here as pseudo code:
const MainStruct = struct {
// Either the dereferenced item:
active_item: SubStruct,
// OR the pointer to the item:
active_item: *SubStruct,
// Here is the cache list
item_cache: std.AutoHashMap(u32, SubStruct),
// ... imagine several more fields to follow ...
};
const SubStruct = struct {
number: u32,
string: []const u8,
};
fn setActiveStruct() !void {
// ... MainStruct and SubStruct's already have been created and the latter added
// to the HashMap using random ID's (123654, 346562, 8867563 ...)
// Not I want to set the MainStruct.active to the SubStruct stored at ID 346562
// Either this one to receive pointer to SubStruct (*SubStruct)
main_struct.active_item = main_struct.item_cache.getPtr(346562).?;
// Or this to receive dereferenced item SubStruct
main_struct.active_item = main_struct.item_cache.getPtr(346562).?.*;
// ... changes to main_struct.active_item are possible and likely. An item which has been
// active before could become active again in a later turn of the main event loop
}
Both cases work, thats not the thing. I just want to know what is “better” regarding to performance, memory management, robustness etc.; or what the pros and cons are for each version.
Since my experience regarding those low level things is not very deep (though, still evolving, thanks mainly to Zig), I’m happy for some feedback or even to get taught a lesson because the whole approach is bullshit ![]()