Doubling a number - shift left vs. multiplication
And here is the 3rd option:
int size = length * 2; // Comment explaining what is 2 or what means this multiplication
And this must be the best option. As it is readable and easy to understand what you want to do.
As for performance, compilers are generating pretty optimized code, so no need to worry for such a simple operation.
If you have any concerns concerning overflow you can use checked
block.
EDIT As mentioned by many others just use any meaningful variable instead of 2
here.
Which is more readable to your average programmer:
int size = length * 2;
int size = length << 1;
Unless they come from a strong C++ bit tweaking background I'd wager your average programmer knows immediately what the first line does (it even has the number "2" for "double" in it) but would have to stop and pause for the second line.
In fact I'd feel inclined to comment the second line explaining what it does which seems redundant when you can get the code do the talking as in the first line.
The idea that <<
is faster than multiplication is reasoning as though the .NET jit compiler is actually a poorly optimized C compiler written in the 1970's. Even if it were true, the difference would be measured in picoseconds at this point in time, even if there were a difference, which there probably is not.
Write code so that it is easy to read. Let the compiler take care of the pico-optimizations. Optimize your code based on profiling realistic scenarios, not on second guessing what the compiler will generate.
Furthermore, the shift operators do not have the same semantics as multiplication. For example, consider the following sequence of edits:
Original program by Jill:
int x = y * 2;
Edit by Bob: Silly Jill, I'll make this "faster":
int x = y << 1;
Edit by Larry the Intern: Oh, we have a bug, we're off by one, let me fix that:
int x = y << 1 + 1;
and Larry has just introduced a new bug. y * 2 + 1 is different than y << 1 + 1; the latter is actually y * 4.
I have seen this bug in real live production code. It is very easy to mentally get into the mindset that "shifting is multiplication" and forget that shifting is lower precedence than adding, whereas multiplication is higher precedence.
I have never once seen someone get arithmetic precedence wrong who multiplied by two by writing x * 2. People understand the precedence of + and *. Lots of people forget what the precedence of shifting is. Are the picoseconds you don't actually save worth any number of potential bugs? I say no.