0

I mean, does something, for example in C#, like

String test = "Test";
txtCtrl.Text = test;

consumes more RAM than just

txtCtrl.Text = "Test";

?

As it's said, a variable is a reserved space in memory. But does that mean that not using a variable won't "reserve" (consume, take) a space in memory?

2
  • Local variables are super cheap in most compiled languages, though slightly more expensive if you turn debugging on because the compiler will avoid some things it could do otherwise. Local variables in optimized code may wind up in registers and almost certainly not be any different than if you used the expression directly. Interpreted and scripting languages may vary, so a fuller answer will probably only come if you narrow down the programming language. Furthermore, local variables are generally stored on the stack, which generally won't incur a cache miss (main memory overhead).
    – Erik Eidt
    Feb 25, 2016 at 4:15
  • Care to explain the downvotes?
    – Yuuza
    Feb 26, 2016 at 14:52

2 Answers 2

6

Maybe.

Depending on your language, and how you use it, and how smart your compiler is, it may or may not take more memory. And even if it does take more memory, it's likely to take less memory (just memory for the reference to the data, rather than the entirety of the data itself).

In the long run, the memory usage is going to be inconsequential to the memory usage of your program, whereas the use of local variables will usually have a significant impact on the readability of your program.

Don't worry about it.

3
  • So in a program that uses many times this same value, it would consume less memory if using a variable with this value, than using the value itself, right? Because the reference is lighter than the value itself?
    – Yuuza
    Feb 25, 2016 at 14:21
  • @BrunoLopes - generally, in most languages.
    – Telastyn
    Feb 25, 2016 at 14:26
  • @BrunoLopes: There are quite a few compilers which are able to merge all copies of "Test", which is even more efficient. But as a rule of thumb, this doesn't matter one iota.
    – MSalters
    Feb 25, 2016 at 16:19
1

Probably.

Because you're assigning the same string to both containers, you're essentially assigning the same string reference. So the string is only stored in memory once, but the reference is stored in two places.

To put it another way, string test holds a reference to a string object. The size of that reference is 4 bytes in a 32 bit CIL environment, and 8 bytes in a 64 bit one. The string itself is however long it is; each Unicode character consumes two bytes, but there is only one string here.

txtCtrl.Text also holds a reference, pointing to the same string object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.