Performance improvement

Igor Mironchik igor.mironchik at gmail.com
Fri May 23 04:58:37 BST 2025


On 23.05.2025 05:52, Jin Liu wrote:
> Igor Mironchik <igor.mironchik at gmail.com> 于2025年5月23日周五 00:21写道:
>> Hi.
>>
>> I'd like to ask you, guys, maybe I'm a dumb a little, and you know how
>> to optimize a following function.
>>
>> inline long long int
>> skipIf(long long int startPos, const QString &line,
>>          const std::function<bool(const QChar &)> &pred,
>>          long long int endPos = -1)
> Since you have a very simple inner loop, changing `pred` from
> `std::function` (essentially a function pointer) to a template
> parameter might help a bit with inlining if `pred` is simple.


Ha, you are right!

#include <QString>
#include <QTest>
#include <QObject>

#include <functional>

inline long long int
skipIf(long long int startPos, const QString &line,
        std::function<bool(const QChar &)> pred,
        long long int endPos = -1)
{
     endPos = (endPos < line.length() && endPos > -1 ? endPos : 
line.length());

     while (startPos < endPos && pred(line[startPos])) {
         ++startPos;
     }

     return startPos;
}

template<class Pred>
inline long long int
skipIfT(long long int startPos, const QString &line,
        Pred pred,
        long long int endPos = -1)
{
     endPos = (endPos < line.length() && endPos > -1 ? endPos : 
line.length());

     while (startPos < endPos && pred(line[startPos])) {
         ++startPos;
     }

     return startPos;
}

class Test : public QObject
{
     Q_OBJECT

private slots:
     void initTestCase()
     {
         m_data = QStringLiteral("abc1234567890de");
     }

     void test_func()
     {
         QBENCHMARK {
             skipIf(3, m_data, [](const QChar &ch){ return ch.isDigit(); });
         }
     }

     void test_template()
     {
         QBENCHMARK {
             skipIfT(3, m_data, [](const QChar &ch){ return 
ch.isDigit(); });
         }
     }

private:
     QString m_data;
};

QTEST_GUILESS_MAIN(Test)

#include "main.moc"

PASS   : Test::initTestCase()
PASS   : Test::test_func()
RESULT : Test::test_func():
      0.000035 msecs per iteration (total: 75, iterations: 2097152)
PASS   : Test::test_template()
RESULT : Test::test_template():
      0.0000045 msecs per iteration (total: 76, iterations: 16777216)
PASS   : Test::cleanupTestCase()

This is a whole order of magnitude.



More information about the kde-devel mailing list