Does This Code Make Me Look Obfuscated?
Okay, last year, when I was but a wee Freshman in High School, during the late spring I was just about done with my Intro To Unix course, and I using Linux like a fanatic. I went up to my programming teacher (one guy taught Unix, C, C++, Data Structures, Assembly, and HTML) and asked him if I could skip Intro to Programming and C I and go right on ahead to C II. He said "Sure, knock yourself out". So I spent that summer learning to code C on my own. Well, come last fall, I coded nothing like the other students. At first it was just a format thing, but I got a program off freshmeat to help me out. Anyway, I still look at problems differently then my teacher. For instance, we recently had an argument over white space removal from a string.
He coded it this way, using two increments (in retrospect, I think I would use this way anyway):
while (str[i] != '\0') {
if (str[j] == ' ') {
++j;
continue;
}
str [i++] = str[j++]
}
And I coded the same problem using one increment, and lots of
strcpys. Given that I only had
strings of 128
characters, I figured it wouldn't be too much extra work for the program. My
teacher didn't think it could be done. Here's how I coded it:
while (str[i] != '\0') {
if (str[i] == ' ') {
strcpy( str + i, str + (i + 1) );
continue;
}
i++;
}
I know, it's probably not the way the
pros do it. But
believe it or not, after clocking both versions of code
100,000 times, my teacher's code was a second faster in
Real Time, but my code had better
User Time and
System Time. Very
weird.
Update: Thanks
Azure Monk for benching the code, I was about to do it myself but it looks like your
benchmark is better then the crude ones I was making. None the less, I find it kind of hard to believe that over all the
recursive function was the fastest method most frequently (my
teacher's code performed the best over all, however). Ahh... it
definitely looks prettiest in
perl anyway...
munificent: My
teachers code would behave that way if it weren't for the fact that when str + j yields a whitespace it just increments j and continues to loop. In
Azure Monks code str is returned to its original memory location after the
loop finishes (it goes its original length - the amount of whitespace removed back in memory, but it would help if it weren't so
obfuscated ;-).