Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[clang-tidy] performance-inefficient-string-concatenation: sometimes code complained to is optimal #54526

Open
loskutov opened this issue Mar 24, 2022 · 3 comments

Comments

@loskutov
Copy link
Contributor

loskutov commented Mar 24, 2022

The check description states that

void f(const std::string&) {}
std::string a("Foo"), b("Baz");
void g() {
    f(a + "Bar" + b);
}

can be rewritten "in a slightly more efficient way" like:

void f(const std::string&) {}
std::string a("Foo"), b("Baz");
void g() {
    f(std::string(a).append("Bar").append(b));
}

In fact, the first version:

  • is (arguably) more readable
  • can lead to at most two allocations in most implementations (new string created for a + "Bar", then b is concatenated using rvalue-overload of operator+, which is equivalent to append), whilst the second one can lead to three allocations (copy of a is created, and then both append calls might lead to reallocation).

Maybe this transformation made sense before C++11, but nowadays it seems that only assignments of form a = [... + ]a + ... are in fact suboptimal.

@loskutov loskutov changed the title [clang-tidy] performance-inefficient-string-concatenation: slm [clang-tidy] performance-inefficient-string-concatenation: sometimes code complained to is optimal Mar 24, 2022
@llvmbot
Copy link
Member

llvmbot commented Mar 24, 2022

@llvm/issue-subscribers-clang-tidy

@Izaron
Copy link
Member

Izaron commented Oct 8, 2022

The first example is really not quite good. There is the "small string optimization", so strings have to be 16+ chars long (on most machines) to provoke any memory allocations. Seems like the check behaves like there is no such optimization.

@loskutov
Copy link
Contributor Author

loskutov commented Oct 9, 2022

I wouldn't take the example literally—"Bar" could be arbitrarily long, and the replacement suggestion would still be senseless.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants