by the-smug-one · 3y ago · 0 comments
Look here for example:
Entry *newVal = malloc(sizeof(Entry)); newVal->key = strdup(key);
Why not:
Entry* e = malloc(sizeof(Entry) + strlen(key));
Now you can also skip the pointer to the key, saving 8 bytes for each entry. Also, just return the hashtable by value, it's so small.
I think that if we're coding in C, C++ or Zig, then it can be fun to actually use the lower level power to our advantage :).
Don't forget +1 for the terminator.
I also think a linked list is not a great data structure in practice. Having the buckets be one of those amortized-O(1)-append heap allocations would be kinder on CPU caches. But, if you are making the string part of the entry, that would also require padding the string length to word boundaries so that the struct gets aligned.
Note also if you kept the length of the string somewhere (which you would need to for my above paragraph's suggestion), you could avoid strcmp-ing hash collisions where the string has different length. Strcmp is going to add up to an expensive thing in this code.
This code also never checks the return value of malloc. Color me unimpressed with this code. (Cue people arguing that checking for malloc failure is a bad idea ... Linux oom killer and high level languages have you spoiled, there i said it! /s)
> Don't forget +1 for the terminator.
Also should check for arithmetic overflow, or at least static_assert that sizeof(Entry) is "too small" to matter. (Hopefully the process of deciding what "too small" should be results in just adding the overflow check.)
It also makes deletion a far more complicated situation. You'd essentially be implementing your own allocator then.
struct KeyedEntry {
struct Entry entry;
char key[]; // flexible array member
};
It's not too much more useful when just using `char`, but for other data types, it's a bit cleaner, since it handles alignment/padding better.[1]: https://en.wikipedia.org/wiki/Flexible_array_member, or https://beej.us/guide/bgc/html/split/structs-ii-more-fun-wit...
_Edit_: Something like this might not be suitable for the author, since they did mention how they wanted each `struct` to have a fixed size.