For example:
; Method 1
.data
val1 DWORD 10000h
.code
add eax,val1
v.s:
; Method 2
.code
add eax,10000h
Which method would execute faster after being compiled (assembled)?
I’m thinking method 2 would produce faster code because the CPU won’t have to read value from main memory before adding up to eax register. I’m not so clear in my answer, could somebody help?
10000h will be read from memory no matter what – either from its location in the data memory, or from its location in the instruction memory. For smaller constant values CPUs provide special instructions that do not require an additional space for the value being added, but this depends on the specific architecture. The add immediate will probably be faster because of caching: by the time the instruction is decoded, the constant will be in cache, and the addition will be very quick.
Small off-topic note: your example shows a case when an optimizing C compiler would produce a faster code than a hand-written assembly: instead of adding 10000h, optimizer may increment the upper half-word by one, and leave the lower half-word as is.