std::string::assign vs std::string::operator=

前端 未结 2 1960
无人共我
无人共我 2020-12-11 15:50

I coded in Borland C++ ages ago, and now I\'m trying to understand the \"new\"(to me) C+11 (I know, we\'re in 2015, there\'s a c+14 ... but I\'m working on an C++11 project)

2条回答
  •  旧巷少年郎
    2020-12-11 16:20

    I tried benchmarking both the ways.

    static void string_assign_method(benchmark::State& state) {
      std::string str;
      std::string base="123456789";  
      // Code inside this loop is measured repeatedly
      for (auto _ : state) {
        str.assign(base, 9);
      }
    }
    // Register the function as a benchmark
    BENCHMARK(string_assign_method);
    
    static void string_assign_operator(benchmark::State& state) {
      std::string str;
      std::string base="123456789";   
      // Code before the loop is not measured
      for (auto _ : state) {
        str = base;
      }
    }
    BENCHMARK(string_assign_operator);
    

    Here is the graphical camparitive solution. It seems like both the methods are equally faster. The assignment operator has better results.

    Use string::assign only if a specific position from the base string has to be assigned.

提交回复
热议问题