映射查找函数调用 Vs 将查找缓存为静态变量

map lookups function calls Vs caching the lookup as a static variable

本文关键字:查找 静态 变量 缓存 函数调用 Vs 映射      更新时间:2023-10-16

函数版本一,map stl查找一次并保存在局部静态变量中

inline const string & dataInputPath()
{
    static string inputpath = Mngr.getStr("input");
    return inputpath;
}
函数

版本二,每次调用函数时都会循环

inline const string & dataInputPath()
{
    return Mngr.getStr("input");
}

我有两个函数调用,我想知道

  1. 什么被认为更合适?
  2. 优点和缺点?
  3. 您更喜欢使用哪一个,为什么?
  4. 如果有办法将结果缓存为右值getStr返回类型const string&

首先,一旦调用了 dataInputPath,即使映射中的值发生了更改,该值也不会更新。

我只会直接从地图中检索值。如有必要,将其留给调用代码以合理的方式缓存值。

既然键"输入"是硬编码的,为什么不只使用全局input_string变量呢?