Skip to content

Commit

Permalink
Optimize for case where target is less than or equal to source string.
Browse files Browse the repository at this point in the history
- Move the target into the source rather than copy and skip allocating.
- Add tests for each case of target length
  • Loading branch information
jackdelv committed Oct 29, 2024
1 parent 19984dd commit b6dc378
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
14 changes: 11 additions & 3 deletions system/jlib/jstring.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 12 additions & 2 deletions testing/unittests/jlibtests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down

0 comments on commit b6dc378

Please sign in to comment.