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
    SW Missouri
    Posts
    17,308
    Rep Power
    25

    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
    13,435
    Blog Entries
    7
    Rep Power
    20

    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
    cenosillicaphobia: the fear for an empty beer glass

Similar Threads

  1. parseInt() vs. intValue()
    By JavaPilot in forum New To Java
    Replies: 5
    Last Post: 02-04-2009, 08: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
  •