#include <iostream>
#include <string>
static uint32_t s_AllocCount = 0;
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 << std::endl;
}
int main()
{
std::string name = "Yan Chernikov";
PrintName(name);
std::string firstName = name.substr(0, 3);
std::string lastName = name.substr(4, 9);
std::cout << s_AllocCount << " allocations" << std::endl;
std::cin.get();
}
PrintName(name);
std::string firstName = name.substr(0,3);
std::string lastName = name.substr(4,9);
#include <iostream>
#include <string>
static uint32_t s_AllocCount = 0;
void* operator new(size_t size)
{
s_AllocCount++;
std::cout << "Allocating " << size << " bytes\n";
return malloc(size);
}
void PrintName(std::string_view name)
{
std::cout << name << std::endl;
}
int main()
{
std::string name = "Yan Chernikov";
#if 0
std::string firstName = name.substr(0, 3);
std::string lastName = name.substr(4, 9);
#else
std::string_view firstName(name.c_str(), 3);
std::string_view lastName(name.c_str() + 4, 9);
#endif
PrintName(firstName);
PrintName(lastName);
std::cout << s_AllocCount << " allocations" << std::endl;
std::cin.get();
}
#include <iostream>
#include <string>
static uint32_t s_AllocCount = 0;
void* operator new(size_t size)
{
s_AllocCount++;
std::cout << "Allocating " << size << " bytes\n";
return malloc(size);
}
void PrintName(std::string_view name)
{
std::cout << name << std::endl;
}
int main()
{
const char* name = "Yan Chernikov";
#if 0
std::string firstName = name.substr(0, 3);
std::string lastName = name.substr(4, 9);
#else
std::string_view firstName(name, 3);
std::string_view lastName(name + 4, 9);
#endif
PrintName("firstName");
PrintName("lastName");
std::cout << s_AllocCount << " allocations" << std::endl;
std::cin.get();
}
const char* name = "Yan Chernikov";
std::string_view firstName(name, 3);
std::string_view lastName(name + 4, 9);
PrintName("firstName");
PrintName("lastName");
我们要做的是修改PrintName函数中的参数为PrintName(std::string_view nam),分配次数就可以从1变成0了。
#include <iostream>
#include <string>
static uint32_t s_AllocCount = 0;
void* operator new(size_t size)
{
s_AllocCount++;
std::cout << "Allocating " << size << " bytes\n";
return malloc(size);
}
void PrintName(std::string_view name)
{
std::cout << name << std::endl;
}
int main()
{
const char* name = "Yan Chernikov";
#if 0
std::string firstName = name.substr(0, 3);
std::string lastName = name.substr(4, 9);
#else
std::string_view firstName(name, 3);
std::string_view lastName(name + 4, 9);
#endif
PrintName(name);
/*PrintName("firstName");
PrintName("lastName");*/
std::cout << s_AllocCount << " allocations" << std::endl;
std::cin.get();
}
像这种在C++中,尤其是多个循环中,使用string是非常影响性能的,如果可以使用string_view,则可以有效提示效率,加快运行速度。
本文系外文翻译,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系外文翻译,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。