Skip to content

Commit

Permalink
src: reduced substring calls
Browse files Browse the repository at this point in the history
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: nodejs#34808
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Joyee Cheung <joyeec9h3@gmail.com>
Reviewed-By: Franziska Hinkelmann <franziska.hinkelmann@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
  • Loading branch information
yashLadha authored and joesepi committed Oct 22, 2020
1 parent 19e492c commit 50fef26
Showing 1 changed file with 15 additions and 8 deletions.
23 changes: 15 additions & 8 deletions src/node_file.cc
Expand Up @@ -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> value) {
Expand Down

0 comments on commit 50fef26

Please sign in to comment.