Wednesday 31 January 2018

C++ boost::replace_all Slowed Me

I've just had myself into a complete frazzle, code yesterday was fast, rendering 120fps, the same code today was struggling to pass 11fps.  And it had me pulling my hair out, of which I have little left to spare.

The problem?

I had been processing strings for specific patterns and only replacing them, so a variable in my engine might have the value "SCORE" and it'd replace the players score value directly into the std::string instance for display.

I however decided I wanted to compound all these reserved words to allow any value to contain any replaced value and also contain formatting, so I could so something like "You have scored %SCORE% today" and it'd just place the number in place.

I turned to boost for this, boost::replace_all, to be specific, and I had about 45 pattern matches which would try to replace any instance of the string in place.

However, this function does not look a head if the predicate is present in the source string, it's in fact very slow.

So code:

const std::string l_Pattern("%SCORE%");
std::string l_Source("You have scored %SCORE% today");
.
.
.
boost::replace_all(
    l_Source,
    l_Pattern,
    Player::Instance()::ScoreAsString());

Would result in very slow performance, my solution is not perform the replace... search for the pattern predicate first:

if ( l_Scource.find(l_Pattern) != std::string::npos )
{
    boost::replace_all(
        l_Source,
        l_Pattern,
        Player::Instance()::ScoreAsString());
}

This latter code runs so much more quickly, I'm far in a way back a head of the speed curve, but I have this lovely dynamic placing of the variables into my rendering controls, and any control can receive any value just by my tweaking the loaded display script, so neat....

Anyway, I hope that helps.  If you want to help me, pop over to my YouTube channel and hit that subscribe button.

No comments:

Post a Comment