Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I do a zero-copy std::string allocation in C++ from a const char * array?

Profiling of my application reveals that it is spending nearly 5% of CPU time in string allocation. In many, many places I am making C++ std::string objects from a 64MB char buffer. The thing is, the buffer never changes during the running of the program. My analysis of std::string(const char *buf,size_t buflen) calls is that that the string is being copied because the buffer might change after the string is made. That isn't the problem here. Is there a way around this problem?

EDIT: I am working with binary data, so I can't just pass around char *s. Besides, then I would have a substantial overhead from always scanning for the NULL, which the std::string avoids.

like image 560
vy32 Avatar asked Dec 09 '22 20:12

vy32


1 Answers

If the string isn't going to change and if its lifetime is guaranteed to be longer than you are going to use the string, then don't use std::string.

Instead, consider a simple C string wrapper, like the proposed string_ref<T>.

like image 96
James McNellis Avatar answered Apr 26 '23 23:04

James McNellis