3 ms·
I'm sorry, but the final version is FAR AND AWAY the worst version of all the code examples on the page. This tiny class in the stack-allocated version is light
by OskarS 5y ago
I'm sorry, but the final version is FAR AND AWAY the worst version of all the code examples on the page. This tiny class in the stack-allocated version is lightweight, takes up very little space, has great cache locality and performs fantastically: all operations on it will probably compile down to one or two instructions touching memory almost certainly in cache.
The heap-allocated version is so much worse! Not only do you have to pay for allocating and freeing it, every time you reference it, you're gonna have to chase a pointer. Imagine if you had 1000 of these in a vector: the stack allocated ones would be right there next to each other, incredibly cache friendly. The heap-allocated ones are gonna cache miss constantly, and there's ZERO chance the loop is going to auto-vectorize. Show this to a data-oriented design person and watch their eyes start bleeding.
And for what? So you can return null? Just return a std::optional from the factory method if you care so much (or boost::optional if you're on pre-C++17). Or use exceptions. Or just accept the fact that it might return the default value. All of those options are better than the final one. If you're choosing to program in C++, it means you should care about performance. If you don't care about performance for this kind of stuff, just use a higher-level language.
- omegalulw 5y ago+1. Even better than optional is StatusOr.