返回静态向量的引用速度较慢

5

我正在设置一个缓存来绘制一些形状。我的方法如下:

我创建了一个名为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
}

这种方法执行速度非常慢,分析工具显示CPU峰值很高,用户界面也非常卡顿。

当我将OrbitCacheManager.h中的getCacheData方法重构为以下内容时:

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);

一切都开始按预期运行。

我的问题是,为什么这个改变会如此显著地增加速度?

我正在使用IOS上的clang c++11。


2
你应该说明编译代码时使用的编译器选项。如果你正在运行未经优化的代码,则所显示的时间是没有意义的。 - PaulMcKenzie
在for循环范围内使用autoauto&的类似问题,可能不是重复,但可能相关。 - Slava
1个回答

7

你可能正在通过引用返回它,但是你正在存储在另一个对象中,因此仍然会进行昂贵的复制:

 auto& cache = getCacheData(type);

如果你希望返回一个引用而不是拷贝,请在返回值前添加&

这样的话,在你需要保留引用而不是拷贝时,代码中的任何地方都可以使用它。


1
@NathanOliver添加了一个参考注释并修正了答案。 - Matthieu Brucher
是的,就是那样!我以为auto已经有了引用。 - andrés
3
auto可以捕获const,但它不会捕获 & - Matthieu Brucher
1
@MatthieuBrucher 如果没有引用,auto 也不会捕获 const。它使用的规则与模板参数推导完全相同。 - Angew is no longer proud of SO
@MatthieuBrucher 是的,auto & 可以变成 const T &,但是普通的 auto 永远不会变成 const T。我觉得这个评论有点误导性。 - Angew is no longer proud of SO
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接