• BeigeAgenda@lemmy.ca
    link
    fedilink
    arrow-up
    23
    arrow-down
    1
    ·
    edit-2
    1 year ago

    No its not the wrong solution! Premature optimization is a waste of time.

    Using if or case are not a solution because they are way too verbose and very easy to introduce an error.

    Modulo is a solution, and using bit-wise and is another faster solution.

    • mryessir@lemmy.sdf.org
      link
      fedilink
      arrow-up
      3
      arrow-down
      13
      ·
      1 year ago

      You call it premature optimization. I call it obvious.

      You use a flat head as a Phillip’s.

      • BeigeAgenda@lemmy.ca
        link
        fedilink
        arrow-up
        6
        ·
        1 year ago

        I call it making assumptions that may be incorrect, and do you know if the compiler will do the optimization anyway in this case?

        • mryessir@lemmy.sdf.org
          link
          fedilink
          arrow-up
          1
          arrow-down
          2
          ·
          edit-2
          1 year ago

          What statement do you flag as assumption? Yes, I do. The modulo operator is only a subset of bit masks. It is more explicit to write:

          if ( (variable &EVEN_MASK) == 0) …

          To act upon even numbers then:

          if ( (variable %2) == 0) …

          How would you name the 2 in the above statement for more expressive power?

          EVEN_MODULO_OP ? That may throw more people off imo.

          • Kogasa@programming.dev
            link
            fedilink
            arrow-up
            8
            ·
            1 year ago

            You shouldn’t rename 2 at all. “Even” has a commonly understood meaning that is instantly recognizable from (variable %2) == 0. The bitmask is an overgeneralization.

          • BeigeAgenda@lemmy.ca
            link
            fedilink
            arrow-up
            2
            arrow-down
            3
            ·
            1 year ago

            I give up, I was wrong to even think about the modulo operator, you are clearly the master programmer. 🥇

            This reminds me of a discussion about the ternary operator ? :, some people think its the one true way of writing code because its just so clear what it does. And I say please use it sparingly because if you start doing nested ternary operators its very hard to unpack what your code does, and I prefer readability over compact code, especially with today’s compilers.