让字符串及字符操作更加快速

视频由up神经元猫 神经元猫的个人空间_哔哩哔哩_bilibili 翻译自 youtube.com/cherno 并发布到👉 【80】【Cherno C++】【中字】如何让C++字符串更快_哔哩哔哩_bilibili 并由我整理。

此本不会讲解为什么std::string会很慢和其背后的细节,只有些例子。

std::string的主要问题之一是 字符串格式化及字符串操作 时需要分配内存

bad例子:

#include <iostream>
#include <string>

static uint32_t s_AllocCount = 0;

// 查看分配多少次内存和如何跟踪这些内存,需要重载new操作符
void* operator new(size_t size) {
    s_AllocCount++;
    std::cout << "allocating: " << size << " bytes\n";
    return malloc(size);
}

void PrintName(const std::string& name) {
    std::cout << name << '\n';
}
    
int main(void) {
    std::string name = "Yan Chernikov";
    
    std::string firstname = name.substr(0, 3);
    std::string lasttname = name.substr(4, 9);
    PrintName(firstname);
    
    std::cout << s_AllocCount << " allocations" << '\n';
    std::cin.get();
}

std::string_views, 它本质上是一个指向内存的指针,就是const char指针,指向其他人拥有的现有字符串,再加上一个size;

  • 比如一个字符串 “hello world”,有一个指向第一个字符(h)的指针,大小是3
  • 再比如有一个指针指向h的指针,大小是4个字节,把我带到那个lastname的开头,大小是9

这是在创建一个进入现有内存的小视窗,而不是分配一个新的字符串用substr()创建一个新的字符串,

我想要的是一个窗口的视图,到一个已有自己内存的字符串

#include <iostream>
#include <string>

static uint32_t s_AllocCount = 0;

// 查看分配多少次内存和如何跟踪这些内存,需要重载new操作符
void* operator new(size_t size) {
    s_AllocCount++;
    std::cout << "allocating: " << size << " bytes\n";
    return malloc(size);
}

void PrintName(std::string_virew name) {
    std::cout << name << '\n';
}
    
int main(void) {
    std::string name = "Yan Chernikov";
    
    std::string_view firstname(name.c_str(), 3);
    std::string_view firstname(name.c_str() + 4, 9);
    PrintName(firstname);
    
    std::cout << s_AllocCount << " allocations" << '\n';
    std::cin.get();
}
Licensed under CC BY-NC-SA 4.0