Let's say the we have an object and that we need to validate the following things -
We have two possibilities for a if statement:
if(greaterThan(Object->text, 0) &&
exists(Objet->dummy) &&
inObject(Object->dummy2, Objet2))
Second if:
if(!greaterThan(Object->text, 0) ||
!exists(Objet->dummy) ||
!inObject(Object->dummy2, Objet2)) {
NOP
} else {
//Do something;
}
Which one would be faster? Thanks in advance.
In general, those two forms are equivalent and a decent compiler would likely compile them to the same final assembly. You should check on your specific compiler, of course. You can take a look at the assembly output of a few compilers here for your problem
For example, the gcc 4.9 output:
void function1() {
if (greaterThan() && exists() && inObject()) {
result = 42;
}
}
gives:
function1():
sub rsp, 8
call greaterThan()
test eax, eax
jne .L13
.L1:
add rsp, 8
ret
.L13:
call exists()
test eax, eax
je .L1
call inObject()
test eax, eax
je .L1
mov DWORD PTR result[rip], 42
jmp .L1
while, the other variant:
void function2() {
if (!greaterThan() || !exists() || !inObject()) {
// NOP
} else {
result = 42;
}
}
leads to identical assembly:
function2():
sub rsp, 8
call greaterThan()
test eax, eax
jne .L28
.L14:
add rsp, 8
ret
.L28:
call exists()
test eax, eax
je .L14
call inObject()
test eax, eax
je .L14
mov DWORD PTR result[rip], 42
jmp .L14
In all cases the compilers produced identical assembly for both options (I simplified it slightly by removing some arguments, but that should be immaterial).