Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

assembly - In x86 what's difference between "test eax,eax" and "cmp eax,0"

Is test eax, eax more efficient than cmp eax, 0? Is there any case that the test eax, eax is necessary where cmp eax, 0 doesn't fulfill requirement?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As Zang MingJie has already said in a comment, test eax,eax is almost identical to cmp eax,0, except that it shorter than cmp, because with cmp you have to supply 0 as an argument. Note that the savings are not very large, because the 2nd operand gets sign-extended to match the size of the 1st operand, so it does not necessarily take a whole 4 bytes to represent that zero.

Now, what you are asking is whether there is any other difference. This is a reasonable question to ask, because cmp is an arithmetic operation, (it performs a subtraction and discards the result,) while test is a logical operation, (it performs a bitwise AND and discards the result,) so one could reasonably suspect that they may modify the Flags register differently.

As it turns out, both instructions modify the Flags register in an almost identical fashion. Both instructions modify the OF SF ZF AF PF and CF bits of the flags register. The test instruction always clears OF and CF, but that's also what cmp against zero does. The only other difference is that the cmp instruction will properly set the obscure AF flag, while the test instruction leaves the contents of that flag undefined. But in the case of cmp eax,0 the AF will always be cleared regardless of the value of eax, so there is nothing that you can learn from a cmp eax,0 that you would not learn from a test eax,eax.

Therefore, I would conclude that there is no situation where test eax,eax will give you something that cmp eax,0 will not, nor vice versa. The two instructions appear to be completely interchangeable for any practical or even not-so-practical purpose, except for saving a byte or two of instruction code.

Using test eax,eax instead of cmp eax,0 shows that you know your assembly. It also shows that you prefer a slightly cryptic, and marginally better performing instruction over a straightforward, understandable instruction. This is the kind of thing that tends to earn bonus points from other geeks, but it has not had any practical usefulness in the real world in the last couple of decades or so.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...