I began to study the device one program recently, entirely written in assembly language (ie no translators in the machine is not used as in high-level languages). So, there I very often meet design type TEST AL, AL
; TEST EAX, EAX
etc.
Here’s a question: why use TEST
, not CMP
? And what’s the point compared with yourself? As far as I know, TEST
uses a logical “AND” (AND
). Clarify please, in these parts, I do not particularly enlightened.
Answer 1, Authority 100%
Commands form test reg, reg
is used to compare the register value to zero. After this operation, the flags zero or sign and parity are set or reset. Why not cmp reg, 0
? Because in the compiled form test reg, reg
on a byte shorter than, well, the speed difference might have.
test
is equivalent to bitwise and
, except that only the flags are modified, but not the operands. Usually it is necessary to find out whether certain bits in the register are set.
A cmp
is equivalent to ordinary subtraction, but likewise modifies the flags, without changing the operands.
Answer 2, Authority 33%
CMP Reg1, Reg2 l = 2 bytes, t = 3 clocks, paired in any assembly line
TEST Reg1, Reg2 l = 2 bytes, t = 3 clocks, paired in any assembly line
CMP Reg, Const l = 3-4 t = 4 byte cycle, paired in any assembly line
The difference in the number of registers used, as a result of optimizing the code and set the changing flagov.T.k. typically uses the following format: TEST Reg1, Reg1, well and accordingly logic – TEST compared with 0:)
Answer 3, authority 19%
flag set after a short instruction test ax, ax 85C0 , makes it easy not only to read the code, due to the simplicity of the form, but also reduce the CPU cost (implementation of AND (logical “AND”) – easy adder on it rezalizovannogo when using CMP (subtraction).
In most cases, after checking for 0 use a conditional branch instruction Jcc (in this case, JE (equal) if the transition is equal (ZF = 1)).
mov ax, 0
test ax, ax; and 0 with 0
je flag_not_set; always taken
mov ax, 1
test ax, ax; and 1 with 1
je flag_not_set; not taken
Here are schematics at the level of micro-instructions: