Skip to content

libtaskmanager: make appData return const reference

Fushan Wen requested to merge work/fuf/imagecomp into master

This speeds up the performance by about 20%.

Benchmark
#pragma GCC push_options
#pragma GCC optimize("O0")

#include <QDebug>
#include <QElapsedTimer>
#include <QHash>
#include <QIcon>
#include <QString>
#include <QUrl>

struct AppData {
  QString id;          // Application id (*.desktop sans extension).
  QString name;        // Application name.
  QString genericName; // Generic application name.
  QIcon icon;
  QUrl url;
  bool skipTaskbar = false;
};

static QHash<int, AppData> appDataCache;
static QHash<int, AppData> appDataCache2;

AppData copy(int i) {
  if (auto it = appDataCache.constFind(i); it != appDataCache.constEnd()) {
    return *it;
  }

  return *appDataCache.emplace(i, QString::number(i), QString::number(i * 2),
                               QString::number(i * 3));
}

const AppData &reference(int i) {
  if (auto it = appDataCache2.constFind(i); it != appDataCache2.constEnd()) {
    return *it;
  }

  return *appDataCache2.emplace(i, QString::number(i), QString::number(i * 2),
                                QString::number(i * 3));
}

int main(int argc, char **argv) {
  QElapsedTimer timer;

  constexpr std::size_t limit = 1000000;
  appDataCache.reserve(limit);
  appDataCache2.reserve(limit);
  int ret = 1;

  timer.start();
  for (std::size_t i = 0; i < limit; ++i) {
    AppData d = copy(i);
  }
  for (std::size_t i = 0; i < limit; ++i) {
    const AppData d = copy(i);
  }
  qDebug() << "copy" << timer.elapsed();

  timer.restart();
  for (std::size_t i = 0; i < limit; ++i) {
    const AppData &d = reference(i);
  }
  for (std::size_t i = 0; i < limit; ++i) {
    const AppData &d = reference(i);
  }
  qDebug() << "reference" << timer.elapsed();

  return 0;
}


#pragma GCC pop_options

Merge request reports

Loading