From e4314dac570a98d1138c63eb25fd4978a44511e5 Mon Sep 17 00:00:00 2001 From: Scott Wolchok Date: Mon, 13 Sep 2021 14:31:36 -0700 Subject: [PATCH] [PyTorch] Reduce heap allocations in OperatorName::setNamespaceIfNotSet (#64673) Summary: Pull Request resolved: https://github.com/pytorch/pytorch/pull/64673 We are now guaranteed to allocate at most one time in this function. ghstack-source-id: 137786392 Test Plan: Previous diff adds test coverage for this function. Reviewed By: dhruvbird Differential Revision: D30813014 fbshipit-source-id: 17d844a1cc8c30574afcc6b0b41b219e62c0b723 --- aten/src/ATen/core/operator_name.h | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/aten/src/ATen/core/operator_name.h b/aten/src/ATen/core/operator_name.h index 2a92697..6440a69 100644 --- a/aten/src/ATen/core/operator_name.h +++ b/aten/src/ATen/core/operator_name.h @@ -34,10 +34,15 @@ struct OperatorName final { // Returns true if we successfully set the namespace bool setNamespaceIfNotSet(const char* ns) { - std::ostringstream oss; if (!getNamespace().has_value()) { - oss << ns << "::" << name; - name = oss.str(); + const auto ns_len = strlen(ns); + const auto old_name_size = name.size(); + name.resize(ns_len + 2 + old_name_size); + // Shift current value of name to the end of the new space. + name.replace(name.size() - old_name_size, old_name_size, name, 0, old_name_size); + name.replace(0, ns_len, ns, ns_len); + name[ns_len] = ':'; + name[ns_len + 1] = ':'; return true; } else { return false; -- 2.7.4