C++学习笔记-SSO

SSO(Small String Optimization)是现代C++标准库中std::string的一种重要优化技术。当字符串较短时,直接在string对象内部存储字符数据,避免动态内存分配,从而提高性能。

SSO基本概念

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <string>

static int s_AllocCount = 0;

void* operator new(size_t size)
{
    s_AllocCount++;
    std::cout << "Allocation: " << size << " bytes" << std::endl;
    return malloc(size);
}

void SSOBasicDemo()
{
    std::cout << "=== SSO Basic Demo ===" << std::endl;
    
    s_AllocCount = 0;
    std::cout << "Initial allocation count: " << s_AllocCount << std::endl;
    
    // 小字符串 - 通常不会分配内存(SSO)
    std::cout << "\nCreating small strings:" << std::endl;
    std::string name = "Jerry Wang 1996"; // 小于或等于15个字符的字符串放在栈上,只在Release模式下,这是VS的特性,Cherno说的
    std::cout << "After creating small string, allocation count: " << s_AllocCount << std::endl;
    
    // 大字符串 - 会分配内存
    std::cout << "\nCreating large strings:" << std::endl;
    std::string longString = "This is a very long string that will definitely exceed the SSO buffer size and cause heap allocation";
    std::cout << "After creating large string, allocation count: " << s_AllocCount << std::endl;
    
    // 字符串大小信息
    std::cout << "\nString size information:" << std::endl;
    std::cout << "sizeof(std::string): " << sizeof(std::string) << " bytes" << std::endl;
    std::cout << "Small string length: " << name.length() << std::endl;
    std::cout << "Large string length: " << longString.length() << std::endl;
    
    // 检查字符串容量
    std::cout << "\nString capacity information:" << std::endl;
    std::cout << "Small string capacity: " << name.capacity() << std::endl;
    std::cout << "Large string capacity: " << longString.capacity() << std::endl;
}

int main()
{
    SSOBasicDemo();
    return 0;
}

SSO实现原理

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
#include <iostream>
#include <string>
#include <cstring>

// 简化的SSO实现示例
class SimpleString
{
private:
    static constexpr size_t SSO_BUFFER_SIZE = 15; // 小字符串缓冲区大小
    
    union
    {
        struct // 大字符串模式
        {
            char* data;
            size_t size;
            size_t capacity;
        } heap;
        
        struct // 小字符串模式
        {
            char buffer[SSO_BUFFER_SIZE + 1]; // +1 for null terminator
        } stack;
    };
    
    bool isSmall() const
    {
        // 使用最后一个字节的最高位作为标志
        return (stack.buffer[SSO_BUFFER_SIZE] & 0x80) == 0;
    }
    
    void setSmall(bool small)
    {
        if (small)
        {
            stack.buffer[SSO_BUFFER_SIZE] &= 0x7F; // 清除最高位
        }
        else
        {
            stack.buffer[SSO_BUFFER_SIZE] |= 0x80; // 设置最高位
        }
    }
    
    size_t getSmallSize() const
    {
        return stack.buffer[SSO_BUFFER_SIZE] & 0x7F; // 获取低7位作为大小
    }
    
    void setSmallSize(size_t size)
    {
        stack.buffer[SSO_BUFFER_SIZE] = (stack.buffer[SSO_BUFFER_SIZE] & 0x80) | (size & 0x7F);
    }
    
public:
    SimpleString() 
    {
        stack.buffer[0] = '\0';
        setSmall(true);
        setSmallSize(0);
    }
    
    SimpleString(const char* str)
    {
        size_t len = strlen(str);
        
        if (len <= SSO_BUFFER_SIZE)
        {
            // 使用SSO
            strcpy(stack.buffer, str);
            setSmall(true);
            setSmallSize(len);
            std::cout << "Using SSO for string: \"" << str << "\"" << std::endl;
        }
        else
        {
            // 使用堆分配
            heap.size = len;
            heap.capacity = len + 1;
            heap.data = new char[heap.capacity];
            strcpy(heap.data, str);
            setSmall(false);
            std::cout << "Using heap allocation for string: \"" << str << "\"" << std::endl;
        }
    }
    
    ~SimpleString()
    {
        if (!isSmall())
        {
            delete[] heap.data;
            std::cout << "Freed heap memory" << std::endl;
        }
    }
    
    // 拷贝构造函数
    SimpleString(const SimpleString& other)
    {
        if (other.isSmall())
        {
            memcpy(stack.buffer, other.stack.buffer, SSO_BUFFER_SIZE + 1);
            std::cout << "Copied SSO string" << std::endl;
        }
        else
        {
            heap.size = other.heap.size;
            heap.capacity = other.heap.capacity;
            heap.data = new char[heap.capacity];
            strcpy(heap.data, other.heap.data);
            setSmall(false);
            std::cout << "Copied heap string" << std::endl;
        }
    }
    
    const char* c_str() const
    {
        return isSmall() ? stack.buffer : heap.data;
    }
    
    size_t size() const
    {
        return isSmall() ? getSmallSize() : heap.size;
    }
    
    size_t capacity() const
    {
        return isSmall() ? SSO_BUFFER_SIZE : heap.capacity - 1;
    }
    
    bool usingSSO() const
    {
        return isSmall();
    }
    
    void print() const
    {
        std::cout << "String: \"" << c_str() << "\"" << std::endl;
        std::cout << "  Size: " << size() << std::endl;
        std::cout << "  Capacity: " << capacity() << std::endl;
        std::cout << "  Using SSO: " << (usingSSO() ? "Yes" : "No") << std::endl;
        std::cout << "  Address: " << (void*)c_str() << std::endl;
    }
};

void SSOImplementationDemo()
{
    std::cout << "=== SSO Implementation Demo ===" << std::endl;
    
    std::cout << "sizeof(SimpleString): " << sizeof(SimpleString) << " bytes" << std::endl;
    
    std::cout << "\n1. Small string (SSO):" << std::endl;
    SimpleString small("Hello");
    small.print();
    
    std::cout << "\n2. Medium string (SSO):" << std::endl;
    SimpleString medium("Hello World123"); // 14 characters
    medium.print();
    
    std::cout << "\n3. Large string (Heap):" << std::endl;
    SimpleString large("This is a very long string that exceeds SSO buffer");
    large.print();
    
    std::cout << "\n4. Copy operations:" << std::endl;
    SimpleString smallCopy = small;
    SimpleString largeCopy = large;
    
    std::cout << "\nSmall copy:" << std::endl;
    smallCopy.print();
    std::cout << "\nLarge copy:" << std::endl;
    largeCopy.print();
}

int main()
{
    SSOImplementationDemo();
    return 0;
}

不同编译器的SSO实现

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <iostream>
#include <string>
#include <vector>

void CompilerSSODemo()
{
    std::cout << "=== Compiler SSO Demo ===" << std::endl;

    // 测试不同长度的字符串
    std::vector<std::string> testStrings = {
        "",                                    // 0 chars
        "a",                                   // 1 char
        "hello",                               // 5 chars
        "hello world",                         // 11 chars
        "hello world!!!",                      // 15 chars
        "hello world!!!!",                     // 16 chars
        "this is a longer string",             // 24 chars
        "this is a much longer string that will definitely use heap allocation" // 70+ chars
    };

    std::cout << "sizeof(std::string): " << sizeof(std::string) << " bytes" << std::endl;
    std::cout << "\nTesting different string lengths:" << std::endl;

    for (size_t i = 0; i < testStrings.size(); ++i)
    {
        const std::string& str = testStrings[i];
        std::cout << "\nString " << i << ": \"" << str << "\"" << std::endl;
        std::cout << "  Length: " << str.length() << std::endl;
        std::cout << "  Capacity: " << str.capacity() << std::endl;
        std::cout << "  Data address: " << (void*)str.data() << std::endl;
        std::cout << "  String object address: " << (void*)&str << std::endl;

        // 检查数据是否在对象内部(SSO的一个指标)
        const char* objStart = reinterpret_cast<const char*>(&str);
        const char* objEnd = objStart + sizeof(std::string);
        const char* dataPtr = str.data();

        bool likelySSO = (dataPtr >= objStart && dataPtr < objEnd);
        std::cout << "  Likely using SSO: " << (likelySSO ? "Yes" : "No") << std::endl;
    }
}

// 测试SSO边界
void SSOBoundaryTest()
{
    std::cout << "\n=== SSO Boundary Test ===" << std::endl;

    // 逐渐增加字符串长度,找到SSO边界
    std::string base = "";

    for (int i = 0; i <= 30; ++i)
    {
        std::string test = base + std::string(i, 'x');

        const char* objStart = reinterpret_cast<const char*>(&test);
        const char* objEnd = objStart + sizeof(std::string);
        const char* dataPtr = test.data();

        bool likelySSO = (dataPtr >= objStart && dataPtr < objEnd);

        std::cout << "Length " << i << ": " << (likelySSO ? "SSO" : "HEAP")
                  << " (capacity: " << test.capacity() << ")" << std::endl;

        // 如果从SSO切换到HEAP,标记边界
        static bool wasSSO = true;
        if (wasSSO && !likelySSO)
        {
            std::cout << "*** SSO boundary appears to be around " << (i-1) << " characters ***" << std::endl;
            wasSSO = false;
        }
    }
}

int main()
{
    CompilerSSODemo();
    SSOBoundaryTest();
    return 0;
}

SSO性能测试

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include <iostream>
#include <string>
#include <vector>
#include <chrono>
#include <memory>

class PerformanceTest
{
public:
    static void stringCreationTest()
    {
        std::cout << "=== String Creation Performance Test ===" << std::endl;

        const int iterations = 1000000;

        // 测试小字符串创建(SSO)
        auto start = std::chrono::high_resolution_clock::now();
        for (int i = 0; i < iterations; ++i)
        {
            volatile std::string small = "Hello";
        }
        auto end = std::chrono::high_resolution_clock::now();
        auto ssoTime = std::chrono::duration_cast<std::chrono::microseconds>(end - start);

        // 测试大字符串创建(堆分配)
        start = std::chrono::high_resolution_clock::now();
        for (int i = 0; i < iterations; ++i)
        {
            volatile std::string large = "This is a very long string that will definitely cause heap allocation and not use SSO optimization";
        }
        end = std::chrono::high_resolution_clock::now();
        auto heapTime = std::chrono::duration_cast<std::chrono::microseconds>(end - start);

        std::cout << "Small string (SSO): " << ssoTime.count() << " microseconds" << std::endl;
        std::cout << "Large string (Heap): " << heapTime.count() << " microseconds" << std::endl;
        std::cout << "SSO is " << (double)heapTime.count() / ssoTime.count() << "x faster" << std::endl;
    }

    static void stringCopyTest()
    {
        std::cout << "\n=== String Copy Performance Test ===" << std::endl;

        const int iterations = 1000000;

        std::string ssoString = "Hello";
        std::string heapString = "This is a very long string that will definitely cause heap allocation and not use SSO optimization";

        // 测试SSO字符串拷贝
        auto start = std::chrono::high_resolution_clock::now();
        for (int i = 0; i < iterations; ++i)
        {
            volatile std::string copy = ssoString;
        }
        auto end = std::chrono::high_resolution_clock::now();
        auto ssoCopyTime = std::chrono::duration_cast<std::chrono::microseconds>(end - start);

        // 测试堆字符串拷贝
        start = std::chrono::high_resolution_clock::now();
        for (int i = 0; i < iterations; ++i)
        {
            volatile std::string copy = heapString;
        }
        end = std::chrono::high_resolution_clock::now();
        auto heapCopyTime = std::chrono::duration_cast<std::chrono::microseconds>(end - start);

        std::cout << "SSO string copy: " << ssoCopyTime.count() << " microseconds" << std::endl;
        std::cout << "Heap string copy: " << heapCopyTime.count() << " microseconds" << std::endl;
        std::cout << "SSO copy is " << (double)heapCopyTime.count() / ssoCopyTime.count() << "x faster" << std::endl;
    }

    static void stringContainerTest()
    {
        std::cout << "\n=== String Container Performance Test ===" << std::endl;

        const int count = 100000;

        // 测试SSO字符串容器
        auto start = std::chrono::high_resolution_clock::now();
        std::vector<std::string> ssoStrings;
        ssoStrings.reserve(count);
        for (int i = 0; i < count; ++i)
        {
            ssoStrings.emplace_back("Item" + std::to_string(i % 100));
        }
        auto end = std::chrono::high_resolution_clock::now();
        auto ssoContainerTime = std::chrono::duration_cast<std::chrono::microseconds>(end - start);

        // 测试堆字符串容器
        start = std::chrono::high_resolution_clock::now();
        std::vector<std::string> heapStrings;
        heapStrings.reserve(count);
        for (int i = 0; i < count; ++i)
        {
            heapStrings.emplace_back("This is a very long item description number " + std::to_string(i % 100) + " that will cause heap allocation");
        }
        end = std::chrono::high_resolution_clock::now();
        auto heapContainerTime = std::chrono::duration_cast<std::chrono::microseconds>(end - start);

        std::cout << "SSO string container: " << ssoContainerTime.count() << " microseconds" << std::endl;
        std::cout << "Heap string container: " << heapContainerTime.count() << " microseconds" << std::endl;
        std::cout << "SSO container is " << (double)heapContainerTime.count() / ssoContainerTime.count() << "x faster" << std::endl;

        // 内存使用估算
        size_t ssoMemory = ssoStrings.size() * sizeof(std::string);
        size_t heapMemory = heapStrings.size() * sizeof(std::string);

        // 估算堆分配的额外内存
        for (const auto& str : heapStrings)
        {
            if (str.capacity() > 15) // 假设SSO阈值为15
            {
                heapMemory += str.capacity();
            }
        }

        std::cout << "Estimated SSO memory usage: " << ssoMemory / 1024 << " KB" << std::endl;
        std::cout << "Estimated heap memory usage: " << heapMemory / 1024 << " KB" << std::endl;
    }
};

int main()
{
    PerformanceTest::stringCreationTest();
    PerformanceTest::stringCopyTest();
    PerformanceTest::stringContainerTest();
    return 0;
}

SSO的实际应用和最佳实践

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <algorithm>

// 利用SSO优化的字符串处理类
class OptimizedStringProcessor
{
public:
    // 优化的字符串分割(利用SSO)
    static std::vector<std::string> split(const std::string& str, char delimiter)
    {
        std::vector<std::string> result;
        size_t start = 0;

        for (size_t i = 0; i <= str.length(); ++i)
        {
            if (i == str.length() || str[i] == delimiter)
            {
                if (i > start)
                {
                    // 对于短字符串,这会利用SSO
                    result.emplace_back(str.substr(start, i - start));
                }
                start = i + 1;
            }
        }

        return result;
    }

    // 优化的字符串连接
    static std::string join(const std::vector<std::string>& strings, const std::string& separator)
    {
        if (strings.empty()) return "";

        // 预计算总长度以避免多次重新分配
        size_t totalLength = 0;
        for (const auto& str : strings)
        {
            totalLength += str.length();
        }
        totalLength += separator.length() * (strings.size() - 1);

        std::string result;
        result.reserve(totalLength);

        for (size_t i = 0; i < strings.size(); ++i)
        {
            if (i > 0) result += separator;
            result += strings[i];
        }

        return result;
    }

    // 字符串缓存(利用SSO减少小字符串的内存开销)
    class StringCache
    {
    private:
        std::unordered_map<std::string, std::string> cache;

    public:
        const std::string& getOrCreate(const std::string& key, std::function<std::string()> factory)
        {
            auto it = cache.find(key);
            if (it != cache.end())
            {
                return it->second;
            }

            auto result = cache.emplace(key, factory());
            return result.first->second;
        }

        void printStats() const
        {
            size_t ssoCount = 0;
            size_t heapCount = 0;

            for (const auto& [key, value] : cache)
            {
                // 简单的SSO检测(基于长度)
                if (key.length() <= 15 && value.length() <= 15)
                {
                    ssoCount++;
                }
                else
                {
                    heapCount++;
                }
            }

            std::cout << "Cache stats:" << std::endl;
            std::cout << "  Total entries: " << cache.size() << std::endl;
            std::cout << "  Likely SSO entries: " << ssoCount << std::endl;
            std::cout << "  Likely heap entries: " << heapCount << std::endl;
        }
    };
};

// SSO友好的数据结构设计
struct Person
{
    std::string firstName;  // 通常较短,利用SSO
    std::string lastName;   // 通常较短,利用SSO
    std::string email;      // 可能较长,但很多情况下仍能利用SSO
    std::string phone;      // 通常较短,利用SSO

    Person(const std::string& first, const std::string& last,
           const std::string& mail, const std::string& ph)
        : firstName(first), lastName(last), email(mail), phone(ph) {}

    std::string getFullName() const
    {
        // 对于大多数姓名,这会利用SSO
        return firstName + " " + lastName;
    }

    void print() const
    {
        std::cout << "Person: " << getFullName() << std::endl;
        std::cout << "  Email: " << email << std::endl;
        std::cout << "  Phone: " << phone << std::endl;

        // 分析SSO使用情况
        auto checkSSO = [](const std::string& str, const std::string& name) {
            const char* objStart = reinterpret_cast<const char*>(&str);
            const char* objEnd = objStart + sizeof(std::string);
            const char* dataPtr = str.data();
            bool likelySSO = (dataPtr >= objStart && dataPtr < objEnd);
            std::cout << "  " << name << " likely using SSO: " << (likelySSO ? "Yes" : "No")
                      << " (len: " << str.length() << ")" << std::endl;
        };

        checkSSO(firstName, "firstName");
        checkSSO(lastName, "lastName");
        checkSSO(email, "email");
        checkSSO(phone, "phone");
    }
};

void PracticalApplicationsDemo()
{
    std::cout << "=== Practical Applications Demo ===" << std::endl;

    // 1. 字符串分割和连接
    std::cout << "1. String processing:" << std::endl;
    std::string csv = "apple,banana,cherry,date,elderberry";
    auto parts = OptimizedStringProcessor::split(csv, ',');

    std::cout << "Split result:" << std::endl;
    for (const auto& part : parts)
    {
        std::cout << "  \"" << part << "\" (len: " << part.length() << ")" << std::endl;
    }

    auto rejoined = OptimizedStringProcessor::join(parts, " | ");
    std::cout << "Rejoined: " << rejoined << std::endl;

    // 2. 字符串缓存
    std::cout << "\n2. String cache:" << std::endl;
    OptimizedStringProcessor::StringCache cache;

    // 添加一些短字符串(利用SSO)
    cache.getOrCreate("user1", []() { return std::string("Alice"); });
    cache.getOrCreate("user2", []() { return std::string("Bob"); });
    cache.getOrCreate("user3", []() { return std::string("Charlie"); });

    // 添加一些长字符串
    cache.getOrCreate("desc1", []() { return std::string("This is a very long description that will not fit in SSO buffer"); });
    cache.getOrCreate("desc2", []() { return std::string("Another long description that requires heap allocation"); });

    cache.printStats();

    // 3. 人员数据结构
    std::cout << "\n3. Person data structure:" << std::endl;
    std::vector<Person> people = {
        {"John", "Doe", "john.doe@email.com", "123-456-7890"},
        {"Jane", "Smith", "jane.smith@company.com", "098-765-4321"},
        {"Bob", "Johnson", "bob.johnson@verylongcompanyname.com", "555-123-4567"}
    };

    for (const auto& person : people)
    {
        person.print();
        std::cout << std::endl;
    }
}

void BestPracticesDemo()
{
    std::cout << "=== Best Practices Demo ===" << std::endl;

    std::cout << "SSO Best Practices:" << std::endl;
    std::cout << "1. Keep strings short when possible (< 16 characters typically)" << std::endl;
    std::cout << "2. Use string literals and const strings for fixed text" << std::endl;
    std::cout << "3. Avoid unnecessary string concatenations that exceed SSO threshold" << std::endl;
    std::cout << "4. Consider string_view for read-only string parameters" << std::endl;
    std::cout << "5. Use reserve() for strings that will grow beyond SSO size" << std::endl;
    std::cout << "6. Profile your specific use case - SSO thresholds vary by implementation" << std::endl;

    // 演示最佳实践
    std::cout << "\nDemonstrating best practices:" << std::endl;

    // 好的做法:短字符串
    std::string shortId = "ID123";
    std::string shortName = "Alice";
    std::cout << "Good: Short strings (ID: " << shortId.length() << " chars, Name: " << shortName.length() << " chars)" << std::endl;

    // 需要注意的做法:字符串连接
    std::string combined = shortName + " " + shortId; // 仍然较短,可能使用SSO
    std::cout << "Combined string: \"" << combined << "\" (len: " << combined.length() << ")" << std::endl;

    // 预分配大字符串
    std::string largeBuffer;
    largeBuffer.reserve(1000); // 预分配避免多次重新分配
    std::cout << "Pre-allocated large buffer capacity: " << largeBuffer.capacity() << std::endl;
}

int main()
{
    PracticalApplicationsDemo();
    BestPracticesDemo();
    return 0;
}

总结

  1. SSO基础:Small String Optimization,小字符串优化技术
  2. 工作原理
    • 短字符串直接存储在string对象内部
    • 避免动态内存分配
    • 使用union或类似技术实现
    • 通过标志位区分SSO和堆模式
  3. 性能优势
    • 减少内存分配/释放开销
    • 提高缓存局部性
    • 加快字符串拷贝速度
    • 降低内存碎片
  4. 实现细节
    • 不同编译器有不同的SSO阈值(通常15-23字符)
    • 使用union存储数据和元信息
    • 标志位标识当前模式
    • 自动在SSO和堆模式间切换
  5. 实际应用
    • 短标识符和名称
    • 配置键值
    • 日志标签
    • 网络协议字段
  6. 最佳实践
    • 保持字符串简短
    • 避免不必要的长字符串连接
    • 使用string_view减少拷贝
    • 预分配大字符串缓冲区
    • 了解目标平台的SSO阈值
updatedupdated2025-09-202025-09-20