37 points · by nalgeon · 3y ago · 51 comments
result := make([]unit64, 0, len(elements))
in the old func. I think that the way it is written, it will continually have to be expanded as the backing array exceeds its capacity (in the course of append() calls).And as others have pointed out, maybe use an empty struct (as opposed to a bool or empty interface) as the map value type. Also TIL about make(map[T]S, len) - didn’t know you could set len, or at least hadn’t seen it in practice, but it was suggested here and I think it would likely help as well.
Edited: I forgot to set len to 0.
std::vector<int> elems;
elems.reserve(max_bound_num_of_elems);
// do some push_back()'s
elems.shrink_to_fit();
Is there anything similar in Go?“Requests the container to reduce its capacity to fit its size.
“The request is non-binding, and the container implementation is free to optimize otherwise and leave the vector with a capacity greater than its size.
“This may cause a reallocation, but has no effect on the vector size and cannot alter its elements.”
arr := make([]uint64, estimatedLength)
...
arr = arr[:actualLength]There is a difference in Go’s slices between length and capacity. Length is the number of elements in the slice, and capacity is the number of elements that can fit in the backing array (so len <= cap).
Replacing
encountered := map[uint64]bool{}
with encountered := make(map[uint64]bool, len(elements))
Should be faster.Golang Hashmaps initially have one bucket with a size of 8. If more elements are added new buckets are created.
So giving a hint to initialize a correct number of things should always be faster.
Others in this thread have mentioned that computing the hash takes time. This is true. Let n be the size of the array. When n in small, the (constant) overhead of computing the hash >> O(n * log n) sorting. Now, consider what happens as n becomes large: Virtually every access becomes a cache miss. The (constant) overhead of a cache miss is >> O(n * log n). At the time, I did the math, and determined that n would need to be some unreasonably gargantuan quantity (on the order of the number of stars in the visible universe) before log n is big enough to overtake the effects of cache misses.
An empty interface occupies 16 bytes. Perhaps the author meant an empty struct which consumes nothing.
Mistakes on internet are corrected in very harsh ways, and many times rarely forgiven.
But hey, keep writing, keep learning, keep reflecting and taking feedbacks to improve. Everyone does this
Maps don't preserve order. The benchmark also is using 10 element slices. That is likely too small to get performance improvements via map lookup and I think the benchmark would still favor unsorted slices over maps.
I'm afk but I suggest using map[uint64]struct{} to reduce memory usage over map[uint64]bool and I recommend benchmarking different sized source slices. 10 items is nothing. Bump that up a few orders of magnitude. There is no way 10 element slices are what they are seeing in production that is causing memory pressure. Still, if the problem is memory, an in-place sort is better that a full copy as a map. And as the author suggests, cpu caching should help with the slice operations.
Author covers both of these comments in the article (though they don't disclose how large their "larger" slice is). (edit: actually I misread you, sorry. You're right about empty structs vs interface).
> Maps don't preserve order
The author's approach using maps preserves order in the result, they are comparing the approach to the sort solution which does not preserve order, not claiming that maps themselves preserve order.
But do those arrays need to contain duplicates, or the code can be changed elsewhere to not generate them?
I actually need them sorted as well hence they are added to an array, and deduplicated.
I had a look and didn’t see any obvious way to eliminate them hence the initial function, and the subsequent faster one.
if !encountered[elements[v]] == true {
is a double negative and hard to understand. I'd write it as if !encountered[elements[v]] {
or if you must use the bare bool, if encountered[elements[v]] == false {having to rehash several times is nasty
Edit: yep - https://go.dev/ref/spec#Making_slices_maps_and_channels
> map of type T with initial space for approximately n elements
That "approximately" isn't great there. Nobody wants "approximately". If "exactly" is difficult - which it might be in many conceivable designs for this data structure - then what you want to offer is "at least".
If I'm a programmer and I know I want to put all 623 of these Doodads in the data structure, offering me a way to get a data structure with space for exactly 623 is great. One with space for at least 623 is fine, whereas approximately 623 is barely useful. Should I try asking for 624 in case that helps ? Do I need to dig into the detailed implementation to figure out, OK, 700 will definitely ensure 623 will fit ?
Either way properly sizing the hashmap is a good idea. Though load factor needs to be take in account, and I’m not sure whether the average hashmap multiplies the capacity by the maximum load factor in order to ensure there’s actually space for the number of items intended. I’d hope so, but…
And if you need to preserve order of elements, there is always sort.Stable!
For a list of plain uin64 sort and stable sort would produce the same output.
Even if you attached some other information to distinguish them, for the purpose of deduplicating you want the values with the same key to be in sequence. Stable sort could help you to choose whether you keep the first or last of the duplicate, but the initial order of unique elements would be lost just like with regular sort.
Edit: I see now that the original article meant preserving output order. And i have not clarified that i meant input order.