From 50fef261aa969443eb1ba477e1b0dff36ceea783 Mon Sep 17 00:00:00 2001 From: Yash Ladha Date: Mon, 17 Aug 2020 16:23:01 +0530 Subject: [PATCH] src: reduced substring calls Reduced the number of substring calls by 1 as it is a linear time complexity function. Thus having a larger path might lead to decrease in performance. Also removed unnecessary string allocation happening in the block. PR-URL: https://github.com/nodejs/node/pull/34808 Reviewed-By: James M Snell Reviewed-By: Joyee Cheung Reviewed-By: Franziska Hinkelmann Reviewed-By: Antoine du Hamel --- src/node_file.cc | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/src/node_file.cc b/src/node_file.cc index 247c1c530428e8..de5c455c7a2a85 100644 --- a/src/node_file.cc +++ b/src/node_file.cc @@ -84,19 +84,26 @@ const char* const kPathSeparator = "\\/"; #endif std::string Basename(const std::string& str, const std::string& extension) { - std::string ret = str; - // Remove everything leading up to and including the final path separator. - std::string::size_type pos = ret.find_last_of(kPathSeparator); - if (pos != std::string::npos) ret = ret.substr(pos + 1); + std::string::size_type pos = str.find_last_of(kPathSeparator); + + // Starting index for the resulting string + std::size_t start_pos = 0; + // String size to return + std::size_t str_size = str.size(); + if (pos != std::string::npos) { + start_pos = pos + 1; + str_size -= start_pos; + } // Strip away the extension, if any. - if (ret.size() >= extension.size() && - ret.substr(ret.size() - extension.size()) == extension) { - ret = ret.substr(0, ret.size() - extension.size()); + if (str_size >= extension.size() && + str.compare(str.size() - extension.size(), + extension.size(), extension) == 0) { + str_size -= extension.size(); } - return ret; + return str.substr(start_pos, str_size); } inline int64_t GetOffset(Local value) {