Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pop or add esp, 4 ? What is the difference?

I saw this question, but I didn't find my answer in it..

So, why would I prefer to use add esp, 4 or add esp, 8 instead of using pop one or two times? Is there any difference (performance, safety, etc.) at all or it's a matter of personal choice?

like image 713
Kiril Kirov Avatar asked May 05 '11 21:05

Kiril Kirov


3 Answers

pop does add esp, 4 too, it simply saves whatever there is on the top of the stack in its operand before. If you need what's on the stack probably pop is faster than mov wherever, [esp]; add esp, 4 but if you simply need to clear the stack add esp, 4 will be fine.

like image 60
BlackBear Avatar answered Oct 31 '22 11:10

BlackBear


Generally, the pop instruction is not equivalent to add esp, N.

pop is used to remove data from the stack and store it in some register; it's also agnostic to which direction the stack grows in, though that's usually not an issue.

Manually adding or subtracting from the stack pointer, esp, doesn't preserve the removed data in a register. It would most likely be more efficient, assuming you don't need to do anything with the data being removed from the stack.

like image 2
Collin Dauphinee Avatar answered Oct 31 '22 12:10

Collin Dauphinee


pop loads data from memory (stack - pointed by ss:[esp]) to a general-purpose register, memory location, or segment register. Anyway, pop uses the processor's load unit to access the stack, while add esp does not use the load unit. Processors since Pentium Pro do Out-of-order execution i.e. execute as many instructions at a cycle as it has internal gates (units) available if these instructions can be executed simultaneously, and, if necessary, re-arranges the order of instructions to utilize the units fully.

Since most processors have just two load units, if you don't need data from the stack (i.e. you want to just skip the data), it is better to add esp, because it is a register-only operation and does not employ a load unit, thus your processor will be able to use the load unit for something else at that time.

like image 1
Maxim Masiutin Avatar answered Oct 31 '22 11:10

Maxim Masiutin