Created
January 25, 2017 17:57
-
-
Save Bueddl/2236f6d400441190db4b30c0868070e6 to your computer and use it in GitHub Desktop.
Implementation of small string optimization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstring> | |
#include <cstdio> | |
class my_string | |
{ | |
private: | |
union | |
{ | |
char inline_buf[16]; // sso | |
char *bufptr; | |
} data_; | |
unsigned int size_; | |
public: | |
my_string() | |
: size_(0) | |
{} | |
my_string& operator=(const char *cstr) | |
{ | |
resize(std::strlen(cstr)+1); | |
if (size_ <= 16) | |
std::memcpy(data_.inline_buf, cstr, size_); | |
else | |
std::memcpy(data_.bufptr, cstr, size_); | |
return *this; | |
} | |
const char& operator[](int i) const | |
{ | |
if (size_ <= 16) | |
return data_.inline_buf[i]; | |
else | |
return data_.bufptr[i]; | |
} | |
void resize(int size) | |
{ | |
if (size_ > 16) | |
delete[] data_.bufptr; | |
size_ = size; | |
if (size_ > 16) | |
data_.bufptr = new char[size_]; | |
} | |
const char *c_str() const | |
{ | |
return &(*this)[0]; | |
} | |
}; | |
int main() | |
{ | |
my_string str; | |
str = "Das ist ein Test"; | |
std::printf("%s\nbuffer address: %p\n\n", str.c_str(), &str[0]); | |
str = "Und noch ein langer Test"; | |
std::printf("%s\nbuffer address: %p\n\n", str.c_str(), &str[0]); | |
str = "SSO"; | |
std::printf("%s\nbuffer address: %p\n\n", str.c_str(), &str[0]); | |
// Possible output: | |
// | |
// Das ist ein Test | |
// buffer address: 0x14ffc20 | |
// | |
// Und noch ein langer Test | |
// buffer address: 0x1500050 | |
// | |
// SSO | |
// buffer address: 0x7fffb5d3ec20 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment