c++ - 哪种重载组合性能最高?

标签 c++ string performance c++11

我有这样一个函数:

void init_str(std::string _s)
{
    std::string s{_s};
}

我想通过允许 const char* 重载来进行优化,以避免创建临时 std::string

void init_str(const char* c)
{
    std::string s{c};
}

但我也可以使用转发。

template<typename T>
void init_str(T&& t)
{
    std::string s{std::forward<T>(t)};
}

但是编译器对重载的偏好是:

  • const char*
  • 转发
  • std::string

那么我应该更喜欢哪种重载组合?

最佳答案

假设使用 c++11 或更高版本,性能最高的解决方案是您尚未尝试过的解决方案:

void init_str(std::string s)
{
  // just use s
}

因为复制省略将确保根本不会构造不必要的临时对象。

使用 std::string(const char*) 构造函数构造 s(总共 1 个构造函数):

init_str("xxx");

这个用拷贝构造函数构造了s:

std::string x; // 1 constructor
init_str(x);   // 1 copy constructor

这用移动构造函数构造了 s

std::string x;            // 1 constuctor
init_str(std::move(x));   // 1 move constructor

这实际上根本没有创建临时文件:

std::string get_str() {
    std::string s("xxx");   // 1 constructor, but...
    return s;               // ...because of RVO it's constructed at the call site
}

init_str(get_str());        // ... which is actually the constructor of s in init_str's arg list
// ... total constructors: 1

关于c++ - 哪种重载组合性能最高?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27580342/

相关文章:

c++ - Visual Studio C++ 异常......怪异

javascript - 在javascript中解析数字比较字符串

java - url 收割机字符串操作

algorithm - 当我只能使用数据库 ID 时,为什么要对 URL 缩短器使用长算法

android - 加密 - 整个文件或单个字段?

c++ - std::future 的错误用法?

c++ - 指针编译器问题

c++ - 为项目文本文件定义宏

ios - Objective C 中的 UserDefaults 数据验证

performance - scala 隐式性能