However, if you really care about performance, you should measure it. Never assume! Who knows what your CPU is actually doing?
The function in question is a version of a Caesar cipher. It returns a character based on an input character, shifted a given number of places left or right. To decipher it, just input the output but use the negative of the shift value.
The main problem when trying to write such a function is how to wrap your values (say 'A' gets shifted 2 places left, it should return 'Y'). You can use a branching method, or you can do some modulo arithmetic. Originally I used a wrapping function like this:
char wrapToRange(char x, char x_min, char x_max)
{
char range = x_max - x_min;
return ((x - x_min) % range + range) % range + x_min;
}
char encipher(char c, int amount)
{
if(isUpper(c) || isLower(c))
{
char result = c + amount % 26;
if(isUpper(c))
return ((result - 'A') % 25 + 25) % 25 + 'A';
if(isLower(c))
return ((result - 'a') % 25 + 25) % 25 + 'a';
}
return c;
}
char encipher2(char c, int amount)
{
if(isUpper(c) || isLower(c))
{
char result = c + amount % 26;
if(isUpper(c))
{
if(result > 90)
result -= 26;
else if(result < 65)
result += 26;
}
else if(isLower(c))
{
if(result > 122)
result -= 26;
else if(result < 97)
result += 26;
}
return result;
}
return c;
}
The first method took 0.014262 seconds on average (there were 100 iterations) to encrypt 100 paragraphs of Lorem Ipsum, while the second took 0.0142116. That's a difference of just 0.00005 seconds with the branching method coming out on top. That's nowhere near statistically significant. The biggest performance increase I found during this was to stop using the wrap around function, which saved around 0.001 seconds.
As you might expect, the I/O is still the bottleneck here. The take away from this post is to identify your bottlenecks, and optimise those, when you can. Don't optimise what you think is slow, optimise what you know is slow; and measure it.
*
While making this post, I realised I could do better with my branching function. I got it down to 0.0134143 seconds. In the grand scheme of things, it's still not much. Here's the new code for that:
char encipher2(char c, int amount)
{
if(isUpper(c) || isLower(c))
{
char result = c + amount % 26;
if(isUpper(c))
{
if(result > 90)
return result - 26;
if(result < 65)
return result + 26;
return result;
}
if(result > 122)
return result - 26;
if(result < 97)
return result + 26;
return result;
}
return c;
}