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

前端 未结 2 1959
无人共我
无人共我 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.

    0 讨论(0)
  • 2020-12-11 16:21

    Both are equally fast, but = "..." is clearer.

    If you really want fast though, use assign and specify the size:

    test2.assign("Hello again", sizeof("Hello again") - 1); // don't copy the null terminator!
    // or
    test2.assign("Hello again", 11);
    

    That way, only one allocation is needed. (You could also .reserve() enough memory beforehand to get the same effect.)

    0 讨论(0)
提交回复
热议问题