3 ms·
"Given an optimizing compiler, the first function (count(a)) is likely to just immediately return the size of the backing vector. The function is nearly free."
by bramblerose 3y ago
"Given an optimizing compiler, the first function (count(a)) is likely to just immediately return the size of the backing vector. The function is nearly free."
As far as I can see, neither gcc nor clang actually do this (unless the array has a fixed size; and even then in the gcc case only if the array is zero or one element long).
Probably still more efficient than a virtual call, but also a lot more complex on both the programmer and the compiler, and a lot harder to debug.
- crickey 3y agoIts only more complex for the programmer because of presumed experiance with polymorphism. Its alot easier to debug a concept because a type either has the function or not there is no overloading or massive inheritance tree where u can easily mistake what is actually being called.
- nemetroid 3y agoIf I remove the inheritance, GCC trunk figures it out at -O2 or above (Clang doesn't figure it out). If I add the inheritance back in, GCC doesn't manage either. https://godbolt.org/z/7bTETsdd1 https://godbolt.org/z/7bTETsdd1
- celrod 3y agoClang does figure it out. Note that clang has a branch, not a loop. It jumps to returning 0, else it continues to do the same thing gcc does. I'd say it figured it out, even if the code isn't as pretty. I tried using `final` to get them to figure out the inheritance case, but devirtualization didn't work when inlining a method defined on a base class. https://godbolt.org/z/h4GEYnzMo https://godbolt.org/z/h4GEYnzMo
- nemetroid 3y agoYou're right, I should have read the Clang output more closely. The part about final inheritance makes sense, too, because otherwise a subclass could override the behaviour and count_concept() would have to support that.
- kllrnohj 3y agohttps://godbolt.org/z/4WxGj7c65 https://godbolt.org/z/4WxGj7c65 Sure looks to me like GCC figures it out. Clang doesn't seem to, though.