The Proof

Here's a program that runs each titlecase algorithm 100,000,000 times on a lightly loaded AMD Athlon  XP 2600+ running at 1916.546 Mhz:

#include <stdio.h>
#include <ctype.h>
int main(int argc, char * argv[])
{
char buf[100];
char *p;
long ss;
long reps = 100000000;

system("date");
strcpy(buf, "i think therefore i am");
printf("%s\n", buf);
for(ss=0; ss < reps; ss++)
{
for(p = buf; (*p = ((p == buf) || *(p-1) == ' ' ? toupper(*p) : *p)) != '\0'; p++);
}
printf("\n");
printf("%s\n", buf);
system("date");
printf("==========================\n");
system("date");
strcpy(buf, "i think therefore i am");
printf("%s\n", buf);
for(ss=0; ss < reps; ss++)
{
for(p = buf; *p != '\0'; p++)
{
if(p == buf) *p = toupper(*p);
if(*(p-1) == ' ') *p = toupper(*p);
}
}
printf("\n");
printf("%s\n", buf);
system("date");
}

And here's the output:

[slitt@mydesk slitt]$ ./a.out
Thu Dec 8 19:12:09 EST 2005
i think therefore i am

I Think Therefore I Am
Thu Dec 8 19:12:48 EST 2005
==========================
Thu Dec 8 19:12:48 EST 2005
i think therefore i am

I Think Therefore I Am
Thu Dec 8 19:13:25 EST 2005
[slitt@mydesk slitt]$

At approximately 39 seconds for the one liner and approximately 37 seconds for the readable version, these two algorithms have substantially the same performance.

Click your browser's back button to go back to Ruby the Right Way.