From 0b5493d4e73f29a5e4b08ec8488922d29b1450a3 Mon Sep 17 00:00:00 2001 From: Eduardo Arias Date: Tue, 6 Aug 2024 06:32:52 -0700 Subject: [PATCH] Minor performance improvements setting up intervention's log - Initialize `log` temporary value on construction instead of doing default initialization and then calling `append`. - Leverage `std::string_view` to replace `const std::string&` parameters in `utils::string::replaceAll` to avoid creating a `std::string` object (and associated allocation and copy) for the string literal`%d` --- src/transaction.cc | 5 ++--- src/utils/string.cc | 8 ++++---- src/utils/string.h | 4 ++-- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/src/transaction.cc b/src/transaction.cc index a19ce88b..7dc8ba24 100644 --- a/src/transaction.cc +++ b/src/transaction.cc @@ -1492,9 +1492,8 @@ bool Transaction::intervention(ModSecurityIntervention *it) { it->status = m_it.status; if (m_it.log != NULL) { - std::string log(""); - log.append(m_it.log); - utils::string::replaceAll(&log, std::string("%d"), + std::string log(m_it.log); + utils::string::replaceAll(log, "%d", std::to_string(it->status)); it->log = strdup(log.c_str()); } else { diff --git a/src/utils/string.cc b/src/utils/string.cc index 8d9e08ff..276fd31f 100644 --- a/src/utils/string.cc +++ b/src/utils/string.cc @@ -254,11 +254,11 @@ unsigned char *c2x(unsigned what, unsigned char *where) { } -void replaceAll(std::string *str, const std::string& from, - const std::string& to) { +void replaceAll(std::string &str, std::string_view from, + std::string_view to) { size_t start_pos = 0; - while ((start_pos = str->find(from, start_pos)) != std::string::npos) { - str->replace(start_pos, from.length(), to); + while ((start_pos = str.find(from, start_pos)) != std::string::npos) { + str.replace(start_pos, from.length(), to); start_pos += to.length(); } } diff --git a/src/utils/string.h b/src/utils/string.h index 55ebc0bd..1cd63296 100644 --- a/src/utils/string.h +++ b/src/utils/string.h @@ -68,8 +68,8 @@ std::vector ssplit(std::string str, char delimiter); std::pair ssplit_pair(const std::string& str, char delimiter); std::vector split(std::string str, char delimiter); void chomp(std::string *str); -void replaceAll(std::string *str, const std::string& from, - const std::string& to); +void replaceAll(std::string &str, std::string_view from, + std::string_view to); std::string removeWhiteSpacesIfNeeded(std::string a); std::string parserSanitizer(std::string a);