Skip to content

Commit 9354812

Browse files
Copilotchhwang
andauthored
Optimize logger string formatting to avoid repeated allocations (#670)
Addresses feedback on PR #668 to eliminate inefficient string operations in the logger's placeholder replacement logic. ### Changes - **Removed repeated `find()` and `replace()` calls** that allocated new buffers on each iteration - **Build output directly into stringstream** by iterating through `header_` once, appending arguments when "%@" placeholders are encountered ### Before ```cpp std::string formattedHeader = header_; while ((pos = formattedHeader.find("%@", pos)) != std::string::npos) { formattedHeader.replace(pos, 2, argStrings[argIndex]); // allocates + copies pos += argStrings[argIndex].length(); ++argIndex; } ss << formattedHeader; ``` ### After ```cpp for (size_t i = 0; i < header_.size(); ++i) { if (i + 1 < header_.size() && header_[i] == '%' && header_[i + 1] == '@' && argIndex < argStrings.size()) { ss << argStrings[argIndex]; ++argIndex; ++i; } else { ss << header_[i]; } } ``` <!-- START COPILOT CODING AGENT TIPS --> --- 💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more [Copilot coding agent tips](https://gh.io/copilot-coding-agent-tips) in the docs. --------- Co-authored-by: copilot-swe-agent[bot] <[email protected]> Co-authored-by: chhwang <[email protected]>
1 parent 77e5659 commit 9354812

File tree

1 file changed

+10
-9
lines changed

1 file changed

+10
-9
lines changed

src/include/logger.hpp

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -92,19 +92,20 @@ class Logger {
9292
std::array<std::string, sizeof...(args)> argStrings = {toStringHelper(std::forward<Args>(args))...};
9393

9494
std::stringstream ss;
95-
std::string formattedHeader = header_;
9695
size_t argIndex = 0;
97-
size_t pos = 0;
9896

99-
// Replace "%@" placeholders
100-
while ((pos = formattedHeader.find("%@", pos)) != std::string::npos && argIndex < argStrings.size()) {
101-
formattedHeader.replace(pos, 2, argStrings[argIndex]);
102-
pos += argStrings[argIndex].length();
103-
++argIndex;
97+
// Replace "%@" placeholders by iterating through header_
98+
for (size_t i = 0; i < header_.size(); ++i) {
99+
if (i + 1 < header_.size() && header_[i] == '%' && header_[i + 1] == '@' &&
100+
argIndex < argStrings.size()) {
101+
ss << argStrings[argIndex];
102+
++argIndex;
103+
++i; // Skip the '@' character
104+
} else {
105+
ss << header_[i];
106+
}
104107
}
105108

106-
ss << formattedHeader;
107-
108109
// Append remaining arguments
109110
for (size_t i = argIndex; i < argStrings.size(); ++i) {
110111
if (delimiter_) {

0 commit comments

Comments
 (0)