Is this approach less resource intensive?
I wrote two simple bits of C and looked at the dissassembly of each.
#include <stdio.h>
int main(int argc, const char * argv[])
{
char x = argv[1][0] == 't';
char y = argv[1][1] == 't';
int foo;
if(x) {
foo = 50;
} else if (y) {
foo = -50;
} else {
foo = 0;
}
printf("%d",foo);
return 0;
}
and
#include <stdio.h>
int main(int argc, const char * argv[])
{
char x = argv[1][0] == 't';
char y = argv[1][1] == 't';
int foo = ( x - (!x && y) ) * 50;
printf("%d",foo);
return 0;
}
Pardon my dissasemblines, I'm on a mac rather than a linux box and so I don't have easy access to gcc -S
so I'm not going to paste them here. When looking at the sequence of events in each that is the if statements or the expression:
This sequence in the first is:
cmpb je movl jmp cmpb je movl jmp movl jmp leaq movl movb
The same reigon in the second version is:
movsbl cmpb movl movb jne movsbl cmpl setne movb movb leaq andb movzbl movl subl imull movl movl movb
The first you can see the compare, jump equal, assign, jump to end, compare, jump equal, assign, jump to end, assign. IN the second, there is a significant amount of operations being done. One can see the andb
, subl
and imull
doing arithmetic operators.
The first will do a small number of comparisons to constants and branches. The second does a significant number of operations.
Is this approach readable to you?
The first is by far more readable and maintainable. Even if the second was to produce more optimal code, I would still write the first as the fractions of a second that are saved in the code are lost many times over when someone comes back to maintain the code and goes WTF?!
Is assigning values in this way common?
No. I have never seen it before this situation.
If 1 is true then in your opinion, does the performance increase
justify the less readable nature of this approach?
As I mentioned, the maintainability of the code is paramount in any situation where someone else may ever have the joys of touching your code later.
As a perl programmer, I recognize the value of hubris:
Hurbis: Excessive pride, the sort of thing Zeus zaps you for. Also the quality
that makes you write (and maintain) programs that other people won't
want to say bad things about. Hence, the third great virtue of a
programmer.
I know I would say bad things about a programmer that writes the second, so I'm not about to do so.