Skip to content

Commit 0200c6e

Browse files
laanwjjanus
authored andcommitted
memusage: Add DynamicUsage for std::string
Add DynamicUsage(std::string) which Returns the dynamic allocation of a std::string, or 0 if none (in case of small string optimization).
1 parent 509875f commit 0200c6e

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

src/memusage.h

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
#include <map>
1616
#include <memory>
1717
#include <set>
18+
#include <string>
1819
#include <vector>
1920
#include <unordered_map>
2021
#include <unordered_set>
@@ -90,6 +91,18 @@ static inline size_t DynamicUsage(const std::vector<T, Allocator>& v)
9091
return MallocUsage(v.capacity() * sizeof(T));
9192
}
9293

94+
static inline size_t DynamicUsage(const std::string& s)
95+
{
96+
const char* s_ptr = reinterpret_cast<const char*>(&s);
97+
// Don't count the dynamic memory used for string, if it resides in the
98+
// "small string" optimization area (which stores data inside the object itself, up to some
99+
// size; 15 bytes in modern libstdc++).
100+
if (!std::less{}(s.data(), s_ptr) && !std::greater{}(s.data() + s.size(), s_ptr + sizeof(s))) {
101+
return 0;
102+
}
103+
return MallocUsage(s.capacity());
104+
}
105+
93106
template<unsigned int N, typename X, typename S, typename D>
94107
static inline size_t DynamicUsage(const prevector<N, X, S, D>& v)
95108
{

0 commit comments

Comments
 (0)