Медленный возврат статического вектора по ссылке

Я настраивал кеш для рисования фигур. Мой подход был следующим:

Я создал класс OrbitCacheManager.h, который выглядел так:

#ifndef OrbitCacheManager_h
#define OrbitCacheManager_h
#include <vector>
#include "cache_0_0.h"
#include "cache_1_0.h"
// many more includes

namespace Core {

   class OrbitCacheManager
   {
   public:
        static std::pair<float,float> getValue(const std::pair<int,int>& type, float phase, float param)
        {
            auto cache = getCacheData(type);
            // interpolate values based on phase and param
            return calculated_value;
        }
   private:
        static std::vector<std::pair<float,float>>& getCacheData(const std::pair<int,int>& type)
        {
            if (type.first == 0 && type.second == 0) return cache_0_0::values;
            if (type.first == 1 && type.second == 0) return cache_1_0::values;
            // etc
        }

Файлы кеша выглядят так:

cache_0_0.h:

#ifndef cache_0_0_h
#define cache_0_0_h 
#include <vector>
namespace Core {
class cache_0_0{
public:
    static std::vector<std::pair<float,float>> values;
};
};
#endif

cache_0_0.cpp:

#include "cache_0_0.h"
using namespace Core;
std::vector<std::pair<float,float>> cache_0_0::values = {
{ 0.000000, 1.000000 },     { 0.062791, 0.998027 }, // etc

Это было сделано так:

for (some phase range) {
    auto v = OrbitCacheManager::getValue(type, phase, param);
    // do something with v
}

Такой подход оказался очень медленным, профилировщик показал много пиковых нагрузок на процессор, а пользовательский интерфейс был очень медленным.

Когда я реорганизовал метод getCacheData в OrbitCacheManager.h к этому:

static std::vector<std::pair<float,float>>* getCacheData(const std::pair<int,int>& type) 
{
    if (type.first == 0 && type.second == 0) return &(cache_0_0::values);

Все начало работать как положено.

Мой вопрос: почему это изменение увеличило скорость так резко?

Я использую Clang C++11 на IOS

1 ответ

Решение

Возможно, вы возвращаете его по ссылке, но храните его в другом объекте, поэтому все еще делаете дорогостоящую копию:

 auto& cache = getCacheData(type);

Вы должны добавить & везде вы возвращаетесь по ссылке и ожидаете сохранить ссылку, а не копию.

Другие вопросы по тегам