开发者

Which one is faster?

(edit: b is an existing boolean)

Is

b = (a > c);

faster than

if (a > c)
    b = true;
  • in general ?
  • and considering the fact that in my case (a > c) is false most of the time ?

edit : I know gains 开发者_StackOverflow中文版will very small even though this part of code will be executed a large number of times. But I'm still intereste in theoretical answer.

Thank you


As Darin says, you should use whatever's more readable to you the speed difference if any will be insignificant... but it's worth noting that they're not equivalent. If this is within a method (so b is a local variable) then the first approach will leave b definitely assigned, whereas the second won't.

Personally I'd just use:

bool b = a > c;

I don't think there's any need for extra brackets, and I prefer to initialize at the point of declaration. If I did use an if block, I'd definitely use braces...


Talking about faster here doesn't make sense in practice as this is a micro optimization that you shouldn't be doing. As far as which one of the two you should be using, use the one that's more readable to you (the first seems more readable to me).


The second one is completely useless. The variable isn't definitely assigned afterwards. So you can't read it and need to assign it again before it is used, which overwrites the result of your assignment.

But I wouldn't worry about such micro optimizations unless really necessary. And in that case you need to profile and inspect the generated assembly code anyways.

AFAIK an optimization similar to this makes sense if you assign to a reference type field(not local variable). Since assignments of reference fields have some additional cost related to interaction with the GC. But with local variables I except no significant difference. The assignment might be slightly faster in some cases, since conditionals problematic if the branch prediction fails.


Apart from the error as mentioned in the other answers, in a managed language like C#, there is absolutely no use in these kind of optimizations. There are so many layers of translations before this code actually gets evaluated. Optimizations like these only make sense if you're in Assembly or Ye Olde C++.


Well, the second version, will take more memory (if we don't consider optimizations etc) on the hard drive - i.e the file will be larger.

The first goes like this:

  1. store a > b in x
  2. mov b,x

The second one will go like this:

  1. store a > b in x

  2. is x true?

    Yes:

  3. b = true

  4. continue execution

    No:

  5. continue execution

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜