Results 1 to 3 of 3
  1. #1
    Courier is offline Member
    Join Date
    Aug 2012
    Posts
    1
    Rep Power
    0

    Default (intValue % 2) vs (intValue & 1)

    They accomplish the same thing (for non-negative integers), (evaluate to 1 or 0 if intValue is odd or even, respectively). Is one faster? I know it is a micro optimisation, but I'm curious. I'm guessing they are compiled into essentially the same thing.

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    18,976
    Rep Power
    28

    Default Re: (intValue % 2) vs (intValue & 1)

    Write a test program, compile it, use the javap command to disassemble the class file and see what code is generated for each.
    In machine code, the AND would be a single instruction. I don't know what the compiler generates for %
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,292
    Blog Entries
    7
    Rep Power
    24

    Default Re: (intValue % 2) vs (intValue & 1)

    Quote Originally Posted by Courier View Post
    They accomplish the same thing (for non-negative integers), (evaluate to 1 or 0 if intValue is odd or even, respectively). Is one faster? I know it is a micro optimisation, but I'm curious. I'm guessing they are compiled into essentially the same thing.
    The javac compiler generates the 'irem' and 'iand' (for ints) instructions for the % and & operators respectively; it leaves it to the jit compiler to do anything smart with them ...

    kind regards,

    Jos
    The only person who got everything done by Friday was Robinson Crusoe.

Similar Threads

  1. parseInt() vs. intValue()
    By JavaPilot in forum New To Java
    Replies: 5
    Last Post: 02-04-2009, 09:39 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •