I have several calls to getenv
in my code(called a lot of times), so I see the potential for an optimization. My question is, does getenv
somehow cache the result internally, or does it query the environment variables on each call?
I have profiled the code, getenv
is not a bottleneck, but I'd still like to change it if it's more efficient.
As a side question, can an environment variable be changed for a program while it is running? I'm not doing that, so in my case caching the result would be safe, it's just curiosity.
Environment variables usually live in the memory of given process so there is nothing to cache there, they are readily available.
As for updates, any component of a running process can call putenv
to updated the environment, you should not cache it for prolonged periods if you expect that to happen.
I doubt it caches the results, environment variables could change from call to call. You can implement that cache yourself:
#include <map>
#include <iostream>
#include <string>
#include <stdexcept>
#include <cstdlib>
class EnvCache {
public:
const std::string &get_env(const std::string &key) {
auto it = cache_entries.find(key);
if(it == cache_entries.end()) {
const char *ptr = getenv(key.c_str());
if(!ptr)
throw std::runtime_error("Env var not found");
it = cache_entries.insert({key, ptr}).first;
}
return it->second;
}
void clear() {
cache_entries.clear();
}
private:
std::map<std::string, std::string> cache_entries;
};
int main() {
EnvCache cache;
std::cout << cache.get_env("PATH") << std::endl;
}
You could invalidate cache entries in case you modify environment variables. You could also map directly to const char*
, but that's up to you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With