13

We just learned in university that you should use '1 << i' instead of 'Math.pow(2, i)' because it is faster when calculating 2^i...

Am I the only one who thinks that this would never get through a code review in a company? I mean it is harder to realize what is going on especially when you didn't went to university lately.

Comments
  • 5
    If I used bit shifting in a PR my lead would be like "Super cool dude... Rejected."

    I'm sure there are certain companies where it would be fine in certain optimization circumstances, but in general I think you're right. Readable and concise: Math.pow or even i * i would usually be preferred.
  • 2
    It depends on the company and who is reviewing the code, and also how performance critical the application is.
  • 5
    Performance is not an issue in this case, because a modern compiler will know better than you what should be used and optimize it automatically for the given target.

    You often hear that ressource bullshit, but you can be sure that the usual dev is not smarter than a modern compiler. Sometimes such premature "human" optimization even prevent compiler optimization strategies, so it may even make it worse.

    The readability depends on the situation. If you're calculating something, use math.pow, if you're bit-fiddling, use 1 << n.
  • 0
    Here’s a fun exercise for you now that you know this.

    Write an algorithm to get the value of the nth bit of a given byte (or really any data type).
  • 2
    Dafuq. Everyone rejecting it should go home.

    Imho 1 << n is way more readable. What is a review for if the code isn't read and understood?

    BUT i guess, too, the compiler is doing this anyway. And secondly, how often do you need powers of 2 in your *average* application?
  • 1
    @daintycode I need powers of 2 regularly. Usually not for calculating, but for creating bit masks or bit strings on the fly, where having constants or lookup tables make no sense.
  • 0
    Bit shifting is ok. If readability is needed just extract it with a good name.
Add Comment