C++让string更快

使用string_view 代替 substr

1.1 substr会给子字符串分配空间,很浪费

下面是一段简单的代码,打印字符串。

#include <iostream>
#include <string.h>
#include <memory>

void printMessage(const std::string& mes)
{
    
    
    std::cout << mes << std::endl;
}
int main(){
    
    

    std::string cripple = "I bloom in the slaughter, like a flower in the dawn";
    std::string first = cripple.substr(0, 24);
    std::string second = cripple.substr(26, 25);
    printMessage(first);
    printMessage(second);
    std::cout << s_str_malloc_count << std::endl;
    return 0;
}

想要知道上面的代码总共分配了几次内存,可以重载new操作符,然后通过变量s_str_malloc_count来知道总共分配了几次。

static size_t s_str_malloc_count = 0;
void* operator new(size_t size)
{
    
    
    std::cout << "Malloc " << size << " bytes\n";
    s_str_malloc_count++;
    return malloc(size);
}

结果总共分配了三次。
在这里插入图片描述

1.2 使用string_view进行优化

下面使用C++17的新特性,string_view,它不像substr那样会重写分配空间,而是只记录一个字符串指针和一个长度。

#include <iostream>
#include <string.h>
#include <memory>

static size_t s_str_malloc_count = 0;
void* operator new(size_t size)
{
    
    
    std::cout << "Malloc " << size << " bytes\n";
    s_str_malloc_count++;
    return malloc(size);
}
void printMessage(std::string_view mes)
{
    
    
    std::cout << mes << std::endl;
}
int main(){
    
    

    std::string cripple = "I bloom in the slaughter, like a flower in the dawn";
    std::string_view first(cripple.c_str(), 24);
    std::string_view second(cripple.c_str() + 26, 25);
    printMessage(first);
    printMessage(second);
    std::cout << s_str_malloc_count << std::endl;
    return 0;
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_46480020/article/details/129034927