Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
581 views
in Technique[技术] by (71.8m points)

c# - Doubling a number - shift left vs. multiplication

What are the differences between

int size = (int)((length * 200L) / 100L); // (1)

and

int size = length << 1; // (2)

(length is int in both cases)

I assume both code snippets want to double the length parameter.

I'd be tempted to use (2) ... so are there any advantages for using (1)? I looked at the edge cases when overflow occurs, and both versions seem to have the same behavior.

Please tell me what am I missing.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...