Зміст курсу
C++ Smart Pointers
C++ Smart Pointers
Performance Considerations With Smart Pointers
Smart pointer overhead
Smart pointers introduce some overhead compared to raw pointers, mainly due to their additional functionalities like reference counting or deletion tracking. Even though this overhead is often negligible, as performance-oriented developers, it's important to be aware of potential performance implications.
Example
Suppose you are working on a legacy embedded application that uses thousands of raw pointers. If you replace all these raw pointers with shared pointers, you may observe a noticeable impact in application throughput.
A better approach would be to slowly refactor your code, measuring performance after each iteration, and choosing a combination of shared and unique pointers based on the use case and applicability.
Minimize shared pointer overhead
Shared pointers are more expensive due to their reference counting mechanism. They increase the reference count whenever a copy is made and decrease it when the pointer goes out of scope or gets reset. This can affect performance, especially in high-frequency scenarios or when using a large number of shared pointers.
The solution is to avoid making unnecessary copies of shared pointers and to only use shared pointers when unique pointers can’t cater to your use case.
Benchmark and profile
Regularly benchmark and profile code segments that use smart pointers to identify bottlenecks and optimize performance. You can use tools like Google Benchmark or Valgrind for this purpose.
Дякуємо за ваш відгук!