From b6dc3788d0ec120ba01bfbaf2b42ca255b7e055f Mon Sep 17 00:00:00 2001 From: Jack Del Vecchio Date: Tue, 29 Oct 2024 07:16:07 -0400 Subject: [PATCH] Optimize for case where target is less than or equal to source string. - Move the target into the source rather than copy and skip allocating. - Add tests for each case of target length --- system/jlib/jstring.cpp | 14 +++++++++++--- testing/unittests/jlibtests.cpp | 14 ++++++++++++-- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/system/jlib/jstring.cpp b/system/jlib/jstring.cpp index 14e26205c1f..1692c94aeef 100644 --- a/system/jlib/jstring.cpp +++ b/system/jlib/jstring.cpp @@ -1072,9 +1072,17 @@ StringBuffer & StringBuffer::replaceString(const char* oldStr, const char* newSt { if (memcmp(buffer, oldStr, oldlen) == 0) { - ensureCapacity(newlen); - memcpy(buffer, newStr, newlen); - curLen = newlen; + if (newlen <= curLen) + { + memmove(buffer, newStr, newlen); + curLen = newlen; + } + else + { + ensureCapacity(newlen); + memcpy(buffer, newStr, newlen); + curLen = newlen; + } } } else diff --git a/testing/unittests/jlibtests.cpp b/testing/unittests/jlibtests.cpp index 53500b8ca15..19d2bfcf4bf 100644 --- a/testing/unittests/jlibtests.cpp +++ b/testing/unittests/jlibtests.cpp @@ -914,12 +914,22 @@ void testEncodeCSVColumn() source.replaceString("ab", "xxx"); CPPUNIT_ASSERT_EQUAL_STR("xxxbxxxxxx", source.str()); - // Search String has same length as source string and matches + // Search string has same length as source string and matches source.set("ababab"); source.replaceString("ababab", "xxxxxx"); CPPUNIT_ASSERT_EQUAL_STR("xxxxxx", source.str()); - // Search String has same length as source string and does not match + // Search string has same length as source string and replace is smaller than source + source.set("ababab"); + source.replaceString("ababab", "xxx"); + CPPUNIT_ASSERT_EQUAL_STR("xxx", source.str()); + + // Search string has same length as source string and replace is larger than source + source.set("ababab"); + source.replaceString("ababab", "xxxxxxxxx"); + CPPUNIT_ASSERT_EQUAL_STR("xxxxxxxxx", source.str()); + + // Search string has same length as source string and does not match source.set("ababab"); source.replaceString("ababac", "xxxxxx"); CPPUNIT_ASSERT_EQUAL_STR("ababab", source.str());