41

SSO of std::string

 5 years ago
source link: https://www.tuicool.com/articles/hit/EZRZbqI
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

No, not single sign-on :stuck_out_tongue: Short string optimization. But before I get into that, little rant… F**K Windows :rage: ! I’ve tried, I really tried to build all my coding examples on Windows. I give up. Even with vcpkg I can’t get cmake to build my $hit! Why is it so easy on Linux with sudo apt install . . . or Mac with brew install . . . to get all the libraries I’m using, but not on Windows?! $100 to anyone (PayPal or Venmo) who gives me simple instructions on how to built my GitHub repository on Windows! No joke!

My next rant will be about encryption and IV’s :stuck_out_tongue: Oh you just wait…

Back on topic! What is short/small string optimization? It’s a way to squeeze some bytes into a std :: string object without actually allocating them on the heap. It’s a hackery involving C++ unions and clever space management. Say sizeof ( std :: string ) is, oh I don’t know, 24 bytes on Mac’s LLVM? The implementation manages to squeeze 22 characters into that (not including the terminating NULL) before having to allocate on the heap. Impressive. Less impressive is GCC’s implementation on Linux, with sizeof ( std :: string ) being 32 bytes but only 15 can be optimized before going to the heap. I used to have this number for Visual Studio’s implementation but… see the rant above :stuck_out_tongue: The capacity of an empty string is the give away for how much you can fit in it before going to the heap :wink:

Check it out yourself on your favorite compiler with the code below!

sso.cpp :

#include <iostream>
#include <string>
 
using namespace std;
 
int main()
{
	auto size = sizeof(string);
	auto capacity = string().capacity();
	auto small = string(capacity, '*');
	auto big = string(capacity + 1, '*');
 
	cout << "sizeof  : " << size << endl;
	cout << "Capacity: " << capacity << endl;
	cout << "Small   : " << small.capacity() << endl;
	cout << "Big     : " << big.capacity() << endl;
}

sizeof  : 24

Capacity: 22

Small   : 22

Big     : 31

Program output (LLVM on Mac).

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK