【问题标题】:Return static vector by reference is slow通过引用返回静态向量很慢
【发布时间】:2019-05-06 01:29:41
【问题描述】:

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

我创建了一个类似 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 峰值,并且 UI 非常滞后。

当我将 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

【问题讨论】:

  • 您应该说明您用于编译代码的编译器选项。如果您正在运行未优化的代码,那么您显示的时间是没有意义的。
  • 在 for range 循环中使用 autoauto &amp; 存在类似问题,可能不是重复但可能相关

标签: c++ c++11 return-by-reference


【解决方案1】:

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

 auto& cache = getCacheData(type);

您应该在通过引用返回的任何地方添加&amp;,并希望保留引用而不是副本。

【讨论】:

  • @NathanOliver 为参考添加了注释并修复了答案。
  • 是的,就是这样!我以为 auto 已经有了引用。
  • auto 可能会捕获 const,但不会捕获 &amp;
  • @MatthieuBrucher auto 没有引用也不会捕获 const。它使用与模板参数推导完全相同的规则。
  • @Angew const std::vector&lt;int&gt;&amp; get() 可以被auto&amp; 捕获,你不需要const,所以在这种情况下捕获它。
猜你喜欢
  • 2012-10-10
  • 2018-07-27
  • 1970-01-01
  • 2019-06-11
  • 2019-11-17
  • 2013-07-07
  • 1970-01-01
  • 2014-06-07
  • 2020-06-18
相关资源
最近更新 更多