|
| 1 | +--- |
| 2 | +title: Hidden Overhead of a Function API by Oleksandr Bacherikov |
| 3 | +date: 2025-03-25 |
| 4 | +tags: |
| 5 | + - Cpp |
| 6 | + - CppCon |
| 7 | +--- |
| 8 | + |
| 9 | +## Introduction |
| 10 | + |
| 11 | +ref: C++ Now 2023 Tony Van Eerd Value Oriented Programming |
| 12 | + |
| 13 | +also C++ Now 2021 and cppcon 2017 |
| 14 | + |
| 15 | +> People are not writing enough functions |
| 16 | +
|
| 17 | +When people finally start writing more functions, we'd prefer to get only the well designed ones! |
| 18 | + |
| 19 | +Well designed function api can have a large impact on performance. |
| 20 | + |
| 21 | +Compare performance by compare the number of instructions generated by a compiler. |
| 22 | + |
| 23 | +ref: Accelerate large-scale applications with BOLT |
| 24 | + |
| 25 | +Disclaimer: only for non-inlined functions. |
| 26 | + |
| 27 | +- System V ABI |
| 28 | +- Microsoft ABI |
| 29 | + |
| 30 | +C++ Core Guidelines seem like a good candidate |
| 31 | + |
| 32 | +ref: C++ Core Guidelines |
| 33 | + |
| 34 | +## Return Value |
| 35 | + |
| 36 | +> For "out" output values, prefer return values to output parameters. |
| 37 | +
|
| 38 | +Reason: A return value is self-documenting, whereas a & could be either in-out or out-only and is liable to be misused. |
| 39 | + |
| 40 | +### Returning std::unique_ptr |
| 41 | + |
| 42 | +Output value is shorter. |
| 43 | + |
| 44 | +Call site. |
| 45 | + |
| 46 | +> Always initialize an object |
| 47 | +
|
| 48 | +Reason: Avoid used-before-set errors and their associated undefined behavior. |
| 49 | + |
| 50 | +Any C++ compiler checks that every execution path in a function ends with a return statement. We just need to return by value. |
| 51 | + |
| 52 | +> Use a `unique_ptr<T>` to transfer ownership where a pointer is needed. |
| 53 | +
|
| 54 | +Reason: Using unique_ptr is the cheapest way to pass a pointer safely. |
| 55 | + |
| 56 | +unique_ptr add some overhead |
| 57 | + |
| 58 | +memory is about 3 times slower than register. |
| 59 | + |
| 60 | +### Wrapper over int |
| 61 | + |
| 62 | +Class return the memory. |
| 63 | + |
| 64 | +ref: Itanimum C++ ABI |
| 65 | + |
| 66 | +Non-trivial Return Value: callee constructs the return value into this address. |
| 67 | + |
| 68 | +For trivial class it returns register. And also size limit. |
| 69 | + |
| 70 | +> If you can avoid defining default operations, do. |
| 71 | +
|
| 72 | +reason: It's simplest and gives the cleanest semantics. It's knows as the rule of zero. |
| 73 | + |
| 74 | +Don't use std::pair and especially `std::tuple`. Named struct is better for both readability and performance. |
| 75 | + |
| 76 | +For `std::unique_ptr`, using `[[always_inline]]` and wrapper the raw pointer. |
0 commit comments