"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Do Smart Pointers in C++ Come with a Significant Memory and Time Overhead?

Do Smart Pointers in C++ Come with a Significant Memory and Time Overhead?

Published on 2024-11-13
Browse:339

Do Smart Pointers in C   Come with a Significant Memory and Time Overhead?

Memory and Time Overhead of Smart Pointers in C

Smart pointers, like std::shared_ptr and std::unique_ptr in C 11, provide automatic memory management and simplify ownership semantics. However, some developers may wonder about the potential performance impact of using smart pointers compared to traditional pointers.

Memory Overhead:

std::unique_ptr imposes memory overhead only if a non-trivial deleter is provided. However, std::shared_ptr always requires additional memory for the reference counter, albeit a relatively small amount.

Time Overhead:

std::unique_ptr incurs time overhead during construction if the provided deleter needs to be copied or the pointer initialized as null, and during destruction to destroy the owned object.

std::shared_ptr experiences time overhead primarily during construction to create the reference counter, during destruction to decrement the reference counter and potentially destroy the object, and during assignment to increment the reference counter. Additionally, these increments/decrements are atomic for thread-safety, further contributing to the overhead.

Impact on Performance:

It's important to note that none of the smart pointers have time overhead during dereferencing, which is typically the most frequent operation for pointers.

In general, the overhead associated with smart pointers is minimal and should not significantly affect code performance. However, continuous creation and destruction of smart pointers can introduce performance bottlenecks.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3