Reputation: 39881
If it is right that working with environment variables is slower than with ordinary variables (in scripting languages?) then how it is explained?
Upvotes: 13
Views: 11148
Reputation: 1713
Yes, on Unix-like systems it's a bit slower, but no system calls.
On Unix-like systems (e.g. Linux), environment variables are passed to processes in a block of memory, in this form:
A=xxx\0B=yyy\0...
It's null-terminated strings in the form of NAME=value
. So to get an environment variable's value, the program has to parse this format to find the string you want, and the value is always a (C-style) string.
In high level programming languages, the runtime (or the script engine) may help you by parsing it once at startup, so later access can be faster, but it's still a dictionary (or map, or whatever your language calls it) lookup. Local variables can usually be accessed without such lookups (it knows where the value is).
Upvotes: 0
Reputation: 59131
Retrieving the value of an environment variable will incur a system call. Ordinary variables are built into the language you are running in, will be in the same address space, and might even be in a CPU register (depending on the language and how it is executed).
It's simply a longer trip to get the data.
That being said, it probably won't be noticeably slow in most scenarios. Unless you're accessing them very often (e.g. constantly using environment variables while in a tight loop, or reading them on a web server during every web request), I wouldn't worry about the performance difference.
Edit:
Turns out the answer is, it depends:
Whether the performance difference actually matters at all or not is situational. And in all cases, you should probably measure the performance difference first for your very specific situation, before spending a lot of time worrying about it (what language? what OS? is it faster if you locally cache, etc).
Upvotes: 14
Reputation: 348
Depends on the language & interpreter design. If the environment is read on initialisation and exposed via standard global variables like in php, there will be no performance difference, with the disadvantage that external changes to the env variable are not seen in the program.
There are however alternative implementations which while more "expensive", offer advantages, performance aside.
Upvotes: 7