Use std::move on stringstream to prevent unnecessary copy. (#138065)

- Takes advantage of C++20's improved handling of move semantics for std::basic_stringbuf.
- Reduces unnecessary copying and improves memory efficiency, especially for long formatted strings.

Benchmark(proof of concept): https://quick-bench.com/q/qohAu0ARH3vSDyKVsoKEfXOO6BI

Pull Request resolved: https://github.com/pytorch/pytorch/pull/138065
Approved by: https://github.com/Skylion007
This commit is contained in:
homorunner 2024-10-16 21:35:07 +00:00 committed by PyTorch MergeBot
parent b72ff35f22
commit a040c4a260
3 changed files with 3 additions and 3 deletions

View File

@ -37,7 +37,7 @@ std::ostream& operator<<(std::ostream & out, const Scalar& s) {
std::string toString(const Scalar& s) {
std::stringstream out;
out << s;
return out.str();
return std::move(out).str();
}
}
namespace at {

View File

@ -124,7 +124,7 @@ inline std::string Join(const std::string& delimiter, const Container& v) {
for (auto i = v.begin(); i != v.end(); ++i, --cnt) {
s << (*i) << (cnt ? delimiter : "");
}
return s.str();
return std::move(s).str();
}
// Replace all occurrences of "from" substring to "to" string.

View File

@ -638,7 +638,7 @@ void initDispatchBindings(PyObject* module) {
if (!op.overload_name.empty()) {
ss << "." << op.overload_name;
}
names.emplace_back(ss.str());
names.emplace_back(std::move(ss).str());
}
return names;