120 points · by jandeboevrie · 3y ago · 139 comments
The issues I see are: a lot of string copying instead of string views, splitting strings into vectors rather than splitting on demand, replacing on the same string repeatedly and collecting into a string before adding it to another string. It seems like their benchmark data has a lot of small lines with set and value commands, which would not be majorly hurt by those issues.
The performance of ~20MB/s is REALLY SLOW for string processing in cpp. A fast but not super optimized c++ program should be getting in the ballpark of 500MB/s.
[0]: https://julien.jorge.st/posts/en/effortless-performance-impr...
But the author is clearly a highly-motivated intermediate C++ user who is taking time to share some key lessons and anyone who keeps that up for long won’t be intermediate for long!
So it’s still a cool blog IMHO :)
It’s backwards compatibility that kills them on performance which is why the 900-IQ C++ shops like Google etc. just go their own way on the hash table because it’s worth it to them to do the extra work.
The operations on the strings are subtly expensive and I was expecting to see them above the accesses to the maps in the perf report. Now they were not and I address the problems in the order of this report, so we will have to wait a bit to discuss them. The intent is also to unroll a scenario of optimization for the reader: measure to get insight, try something, measure again, decide.
If you have the time and the motivation I would love to see a fast but not super optimized version of this program. I tried to keep using the standard library and not going into cryptic code (i.e. trying to keep the code clear for an average programmer), and I stopped when the performance gain became very small, but I am pretty sure we can get better performance if we push further.
I worked on optimizing that version for a little while. The result is a version which takes 30% of the time of the original and a little worse than twice as fast as the best in the repo. That's still disappointingly slow to me, but I'm not great at c++ so I don't really want to take the time to try to improve it further.
Still pretty low-effort but slightly higher cost and benefit is to switch to more modern data structures that have to break a little backwards compatibility to get big wins. Things like Folly’s F14 and Abseil’s collections (Abseil has both faster hash tables and faster tree-style maps).
I think languages like Rust with a little less backwards compatibility burden are shipping with cache-aware and SIMD-exploiting data structures “out of the box” these days, but but my knowledge of e.g. Rust stops short of “read the standard library a bunch of times” so check with someone who has :)
Thus for example, the HashMap in Rust 1.0 is different from the HashMap shipped in any recent Rust, but they both implement the API described in the documentation, the new one is just much faster because it's actually HashBrown, a re-implementation in Rust of Google's Swiss Tables C++ hash map.
Hyrum's Law means that to some extent even though the defined API is narrow, people will write Rust code, by mistake or on purpose which depends on internals that were never guaranteed. For example, sort_unstable_by() is, as its name says, an unstable sort, you should not assume that it leaves ['a', 'A', 'B', 'b'] in the same order when you provide a case-insensitive comparison operator - you should have used sort_by() if you could not accept instability in your sort results.
Rust gets to measure the impact of Hyrum's Law and re-consider potential changes which have large real impact because it does Crater Runs, which compile and test large volumes of Rust software from the crates.io package site and GitHub, with to-be-released Rust versions. If you made a change that you thought was basically a typographical fix, and it's technically not a breaking change by Rust's rules but it blew up 15000 widely used crates, you need to think harder about whether that's OK and most likely revert your change.
C++ has no analogue of the Crater Run as of yet, and it offers a lot of needlessly broad APIs which lock it into choices that are terrible because it promised something that in hindsight nobody cares about, but now you daren't change that.
The ABI promises in real world C++ implementations make this even worse. Rust's Mutex<Option<CompactString>> [[CompactString is a 3rd party library type]] is significantly smaller than a std::mutex on most popular C++ platforms, and yet std::mutex is literally just a mutex, whereas Mutex<Option<CompactString>> is a mutex protecting an optional Small String Optimized string containing up to 24 bytes of UTF-8 encoded string all in line in your smaller data type.
It does in the form of large organizations with large codebases that try out candidate releases and file bug reports.
It's not managed by a central "C++ team" as such if that's what you mean, but there are N independent C++ implementations. At some point we're comparing organizational structure and not technology outcomes.
It's not that the previous practices didn't work, more or less, it's that they were manual and so you couldn't really rely on them. CI is categorically better, despite being in some sense just an automation of what should be existing practice.
There are legitimate use cases that require good performance and some ABI stability guarantees. Like various kinds of closed-source client libraries.
Rust doesn't have to serve those use cases, of course. But "stable ABI is bad" is a very broad statement.
The real problem here is the lack of packaging solutions for systems programming, which are frequently multi-language in some way. And in the case of closed-source use cases, that would look like binary packages. If we had quality dependency management, we would have different options for different use cases and standard libraries could focus on 90% use cases instead of 99.99% ones. Being all things to all users isn't a winning strategy.
std::map<std::string, std::string> m;
(void) m["nonexistent"];
m.size(); // => 1
Is there a historic reason for this strange specification? Or is it just a concession make the "operator=" sugar work better?operator[] returns a reference to a slot in the map which can be read from or assigned to. Since the reference must be valid, you better have allocated a slot in the map that can be written to if the value didn’t exist.
- what is the dummy value? does the value type even have one?
- I don't think index-assignment (or attribute-assignment) is overloadable in C++, so you need `a[b]` to return something which can be assigned to, and proxy values tend to be really wonky (see: `vector<bool>`), so assigning to the result of the indexing would replace the dummy value
m["nonexistent"] = 1;
This would not work if you return a dummy value. from collections import defaultdict
m = defaultdict(int)
m["nonexistent"]
len(m) # => 1
There are examples of the opposite too, though. Ruby's Hash does not insert the entry: m = Hash.new(0)
m["nonexistent"]
m.length # => 0It does if you initialise the hash with a block to do so:
m = Hash.new {|h, k| h[k] = 0}
m["nonexistent"]
m.length # => 1
That is, essentially, what defaultdict does. Just through subclassing (because `dict` does not provide such a fallback, but it has a magic method you can override to customise the mapping's behaviour in that case).if norvig isn't smart enough to use defaultdict without introducing bugs then i'm not either
(I am sure I never reported anything about the sudoku solver, since I never studied it.)
AFAIK basically just 3 wide-spread languages which do this, and they're all known for their idiosyncratic behaviour: C++, Perl, and PHP.
A few languages provide this as opt-in via a subtype (Python's defaultdict) or init (Ruby's Hash.new with a block parameter).
Some more will do it via an opt-in callsite API e.g. Python's `setdefault`, Java's `computeIfAbsent`, Rust's `entry` API.
my $x = $h{$v};
this is not safe because it autovivifies $h{$v} as an ARRAY ref: my $x = $h{$v}[$i];
with respect to idiosyncratic behavior, if a language doesn't have idiosyncratic behavior, it has no reason to exist; it's just gratuitously incompatible syntax for already-available semanticsEspecially annoying when looking up something in a const& map.
The alternative approach could have been to make operator[]= and operator[] different.
foo[bar] += baz;
... needs to provide operator+= with a mutable reference to foo[bar], and a maybe immutable reference to baz.
auto [it, newly_created] = m.try_emplace(key);
Does the same, and gives back more information. For something like `m[key] = value`, you can do `m.insert_or_assign(key, value)`, and save the default construction + assignment when the key was not there.For ordinary lookup you don't want to randomly mutate the map anyway. If your reference to the map is const, you can't use operator[] anyway, fortunately. However `m.at(key)` is not great either when the key not being present is really not exceptional, and the dance with `m.find(key)` is often not too ergonomic. I still suggest to just use `find` here.
operator[] does more than lookup, but there are other functions for the other stuff. It should be pretty clear...?
Comparing to other languages I know, I couldn't think of another where collection[key] denotes insertion.
C++ simply generalized this model to all collections, in line with the overall "better C" design. But then for maps it means that [] has to proactively create an entry if you want []= to work like it does everywhere else.
Similarly, C++ iterators are generalized C pointers, which is also not an ideal abstraction in practice (and why few other languages do it that way).
It is just very convenient (hence the existence of defaultdict in python).
if(auto i = x.find(y); i!=x.end()){
// use i->{first,second}
}
Also ideally you should be able to do this: for(auto [key, value]: x.equal_range(y)) {
}
But infuriatingly, x.equal_range returns a pair instead of some range view so you need some additional infrastructure (either convert the result of equal range into a range or add some begin/end overloads for pair).In practice C++ APIs where you'd naturally write Option<&T> use pointers and are consequently easier to use wrong, this is an example of Rust actually providing improved safety technology (whereas many commonly identified safety differences like bounds checking in Rust are cultural differences)
Some of my favorite alternative hash map implementations are ska::flat_hash_map and ska::bytell_hash_map from https://github.com/skarupke/flat_hash_map. They're fast, and the single header implementation makes them easy to add to a project. For my use cases they generally offer similar performance to abseil and folly F14.
Don't be fooled by the fact that they haven't been updated in ~5 years. I've been using them for nearly that long and have yet to find any bugs.
Check this one out, it's a successor to this idea. Boost also introduced a very performant flat_hash_map in 1.81
And: how often does this even matter? I'd guess very rarely.
In contrast your typical std::unordered_map has indifferent performance with a good hash versus a terrible hash, anything vaguely resembling a working hash will perform similarly (not very well).
Remember "all the defaults are wrong" in C++. That's not literally true, but more often than not, if there's a clownishly obvious mistake possible, C++ made it and you will need to explicitly work around it in your C++ program. In this case, there's no avalanche behaviour in most out-of-box hashes for C++. So the hash for 1, 2, 3 and 4 are extremely similar, and indeed in many cases they turn out to be 1, 2, 3 and 4 respectively. Not a good hash.
[1] https://stackoverflow.com/questions/38304877/why-stdhashint-...
It made a huge difference in one of the programs I was running.
EDIT: I could have sworn they used to also support the ordered versions, but maybe not.
- Hashing can be slower than comparison (or vice-versa), depending on the input. (e.g., imagine if your keys are multi-gigabyte files - hashing them would require reading all of their contents, whereas comparing might only need to read the first few bytes.)
- Ordered maps guarantee good worst-case performance. Unordered maps only guarantee average case. Usually you don't need to care, but with adversarial input you might.
- Ordered maps can guarantee low latency (well, to the extent your allocator can). Unordered maps can't - they suddenly block your program until the whole table is rehashed. Again, usually you don't need to care, but in some situations you might.
- Ordered maps have stable iterators; unordered maps "only" have stable pointers.
- Ordered maps have a guaranteed iteration order that depends solely on their contents; unordered maps don't.
- Any time the ordering itself is useful (see sibling comment)
But that's very unlikely, and in such a contrived scenario it's likely doing a linear std::find() over an array of keys would be as fast or faster anyway, due to better caching/pre-fetching/branch-prediction.
If so, that sounds fairly limiting to me (i.e. potential extra storage - of duplicates, sorting required, etc).
There’s no random access for hash map, in the sense of “give me the fifth element”. If you mean a lookup, like map[key], hash map has an O(1) amortized look up, where as a binary tree has an O(log n) look up, so hash map will generally be faster in this regard.
This is easy to do in all sane hash map designs, and is very fast in a linear design like Abseil's Swiss Tables.
Also sadly C++ std::unordered_map is guaranteed to be not just a hash table but an open hash table, using buckets to keep all the stuff which collided together. This is probably not what you wanted, but too bad that's what was standardized.
It's not that fast, because branching is completely unpredictable when iterating the sparse array (though a very high load factor helps). That's why a few modern hash tables trade an additional indirection on lookup by storing entries in a dense array and making the sparse array an array of indices into that.
It makes iterating the map as efficient as iterating an array (or zipping two depending on data layout), it also saves some memory (especially if the indices array is adaptive), and has the neat side-effect of making the map conserve insertion order (though deletion is a bit of a concern, tradeoffs may have to be made with the other advantages).
std::map actually seems to fit this role better. It works reasonable well for many workloads and types without tuning a bunch of parameters.
Complexity is not a measure of runtime. The performance drawbacks for std::map have to do with cache, not O(log) vs O(1). log(billion) is 30. And that's exactly how many comparisons you have to do, not a constant multiple of that.
With an open addressing hash table, who knows how many steps you will need to find an element. It's even more questionable if it does linked list chaining.
> binary search tree.
It's usually a red black tree and maybe could be a b-tree? "Search tree" is accurate.
IIRC the complexity requirements of std::map preclude a b-tree (or require a binary tree). Though I don't remember the exact reasoning.
abseil's website makes the same claim, though also without justification:
> B-trees have a different implementation from STL std::map containers, which require binary trees commonly implemented as red-black trees.
I mean, I haven’t write red black trees for a while, but it is a type of binary search tree, as far as I remember, isn’t it?
map is definitely not better for random access, with the possible exception of adversarial input: IIRC std::map pretty much requires an rbtree so you get an O(log2(n)) access, while unordered_map is a hashmap so has an O(1) best case but O(n) worst case.
unordered_map might have a better cache friendliness (though that's debatable as IIRC the standard requires closed-hashing), however iterating it is a long series of unpredictable branches (each bucket can be empty or full and the better your hash function the more random it is), std::map requires a lot of pointer-chasing instead but it's all completely predictable.