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

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.)


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.