Skip to content

Commit 4d1d3f4

Browse files
yashLadhaMylesBorins
authored andcommitted
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: #34808 Reviewed-By: James M Snell <[email protected]> Reviewed-By: Joyee Cheung <[email protected]> Reviewed-By: Franziska Hinkelmann <[email protected]> Reviewed-By: Antoine du Hamel <[email protected]>
1 parent 3a401b8 commit 4d1d3f4

File tree

1 file changed

+15
-8
lines changed

1 file changed

+15
-8
lines changed

src/node_file.cc

+15-8
Original file line numberDiff line numberDiff line change
@@ -84,19 +84,26 @@ const char* const kPathSeparator = "\\/";
8484
#endif
8585

8686
std::string Basename(const std::string& str, const std::string& extension) {
87-
std::string ret = str;
88-
8987
// Remove everything leading up to and including the final path separator.
90-
std::string::size_type pos = ret.find_last_of(kPathSeparator);
91-
if (pos != std::string::npos) ret = ret.substr(pos + 1);
88+
std::string::size_type pos = str.find_last_of(kPathSeparator);
89+
90+
// Starting index for the resulting string
91+
std::size_t start_pos = 0;
92+
// String size to return
93+
std::size_t str_size = str.size();
94+
if (pos != std::string::npos) {
95+
start_pos = pos + 1;
96+
str_size -= start_pos;
97+
}
9298

9399
// Strip away the extension, if any.
94-
if (ret.size() >= extension.size() &&
95-
ret.substr(ret.size() - extension.size()) == extension) {
96-
ret = ret.substr(0, ret.size() - extension.size());
100+
if (str_size >= extension.size() &&
101+
str.compare(str.size() - extension.size(),
102+
extension.size(), extension) == 0) {
103+
str_size -= extension.size();
97104
}
98105

99-
return ret;
106+
return str.substr(start_pos, str_size);
100107
}
101108

102109
inline int64_t GetOffset(Local<Value> value) {

0 commit comments

Comments
 (0)