4 ms·
To be perfectly honest what I want to see, for the specific C++ case cited, is std::all_of with a suitable predicate. Let the compiler figure it out. Plugged i
by jeffbee 6y ago
To be perfectly honest what I want to see, for the specific C++ case cited, is std::all_of with a suitable predicate. Let the compiler figure it out.
Plugged it into compiler explorer and clang 10 does unroll the std::all_of version, doing four chars at a time.
- galkk 6y agoExactly that, I was surprised to see that looong for loop definition (I'm not using C++ at all) and wanted to see if there's anything else to simplify. First I found for_each then all_of If anyone is interested, here is simpler version: bool is_ascii_branchy(const std::string_view v) { return std::all_of(v.begin(), v.end(), [](auto i) { return uint8_t(i) < 128;}); }
- im3w1l 6y agoSo I guess this would be the best way to write it if you have a set of long strings most of which are non-ascii, and most such strings having a high proportion of non-ascii? Since then early exit will really help.
- jonstewart 6y agoSTL is great! How’s the performance, though, compared with TFA’s optimistic and hybrid versions?
- cornstalks 6y agoAnd for a fair comparison, here's an imperative loop that's way cleaner than what TFA used: bool is_ascii_branchy(std::string_view v) { for (auto c : v) if (uint8_t(c) < 128) return false; return true; }
- afmos 6y agoClang 10 appears to unroll the loop 4x, but does not perform the optimization from the blog post where comparisons are made 64 bits at a time (rather than 8 bits): https://godbolt.org/z/oefzhx https://godbolt.org/z/oefzhx
- BeeOnRope 6y agoThis doesn't generate anything close to what the author is talking about: it still does character-by-character comparisons. Sure, it has unrolled the loop (but this is nothing to do with std:: and everything to do with what optimizations are enabled by clang at various -O levels), but it hasn't combined 8 individual checks into a single 64-bit wide check of the same cost.
- jeffbee 6y agoAll true. But I’d expect an exceptional justification for the optimization in the article, balanced against readability and maintainability.
- BeeOnRope 6y agoAgreed. As a high performance library function such tricks are par for the course, but you'd hope it wouldn't be sprinkled through ordinary code without good reason. The best of both worlds would be having the compiler transform the canonical std:: version into the fast one under the covers, but that's far from universal with current compiler tech and languages.