Re:Making a Go program 70% faster with a one character change
by a_t48 on Monday November 14, 2022 @04:25PM
(#33601360)
Yup, it's definitely a bit of a code smell if you do. The issue is more the reverse, though - I can't make a mutable map, then hand it by pointer/reference to something that says it wants an immutable map later.
[ Parent
| on HN ]
Re:Making a Go program 70% faster with a one character change
by masklinn on Monday November 14, 2022 @04:28PM
(#33601393)
Not necessarily a bad thing either, things can get odd if you're not the only owner and it's mutated under you unexpectedly.
Re:Making a Go program 70% faster with a one character change
by a_t48 on Monday November 14, 2022 @04:38PM
(#33601543)
That only matters if you're storing it. It mainly just encourages never using a map with constant values. As an API writer it would be neat to be able to accept a `const unordered_map<key, const val>&` to promise "I won't touch the map nor its contents" but doing so mans you aren't compatible with most real world usages of map. It matters also if you want to make a copy of the map. Imagine I want a function `void maybeMakeCopyAndStore(const unordered_map<std::string, const ExpensiveStruct>&`. As I don't want to always make a copy, I don't want to accept a moved value. I would like to promise to my caller that I don't touch the passed in struct. But I also need to be compatible with caller code that likely mutates the values.
Re:Making a Go program 70% faster with a one character change
by a_t48 on Monday November 14, 2022 @04:50PM
(#33601726)
That only matters if you're storing it. The big issue is 99% of code out there uses mutable template types for containers, and if you ever declare a container that doesn't have a mutable template type, you stub your toe as your new container isn't compatible with anyone else's code. You can't even easily copy your way out.
std::unordered_map<std::string, const std::string> m;
m["foo"] = "bar";
std::unordered_map<std::string, std::string> m2 = m;
doesn't compile.
Re:Making a Go program 70% faster with a one character change
by account42 on Tuesday November 15, 2022 @04:03AM
(#33606907)
> That only matters if you're storing it.
Or if you (or something you call) mutate it trough another reference/pointer. Sometimes I wish there was a stronger const where the compiler (and programmer) could actually assume the object is not mutated while that reference/pointer is alive. Of course checking that is no longer doable with just the type system.
> You can't even easily copy your way out.
That depends on the type. std::unordered_maps could provide a copy constructor that does the conversion.
And you can do the copy via iterators, although that is probably not as efficient as it could be because it needs to re-hash the keys.
std::unordered_map<std::string, std::string> m2(m.begin(), m.end());