I'll steal the first sentence from Péter Török's answer but elaborate differently: Not necessarily. It can also decide to just use the raw value 5 instead of myval
in the compiled code.
Treating myval
like a regular variable by allocating space for it in memory can have performance implications that range from miniscule to severe depending on the architecture and how it handles memory.
Working that way, a compiler would emit an instruction that says something along the lines of "load register R with whatever is at the memory location for myval
". The location of myval
as an operand of the instruction, so it comes right out of the same block of data as the instruction itself. On modern CPUs, this value will be readily available on-chip because of instruction prefetch. With the address in hand, the CPU still has to get the value out of memory. That might go quickly if the location is nearby in cache or not so quickly if it isn't. Not only does the CPU have to go off-chip to get the value, doing so might force it to bump other, more useful data out of the cache that will have to be brought back in later. When the program is running under an OS that virtualizes memory, access to that location might cause a page fault, resulting in the program being put to sleep until the required page is brought into RAM via peripheral (e.g., disk) I/O, the program restarted via a context switch and the cache mechanism does whatever it's going to do with it.
By hard-wiring the constant value into the object code, the compiler would emit an instruction like "load register R with the value 5
." Like the memory address described above, the 5
would be an operand to the instruction and available in the same way (i.e., prefetched). That's where the similarity ends, because the CPU now has everything it needs to put the 5
into register R and get on with its business. Since addresses and registers are usually the same size, there's no difference in the number of bytes the instruction occupies and the actual execution takes place with zero chance of the cache misses and page faults that can occur when you go fish something out of memory.
The compiler could, as Péter pointed out, allocate space and a symbol for myval
in debug builds. There wouldn't be any harm in doing this and still hard-wiring its value, since the value remains the same no matter what and the symbol is really just there for us humans to use in debugging.
Note that this only applies to values that can be held in registers, because registers are integers by nature. Other constants will end up in memory.
storage of const object
the source of your question has little value.