How much is %(modulus op.) heavy?

This is a discussion on How much is %(modulus op.) heavy? within the C Programming forums, part of the General Programming Boards category; Hello, I'm wondering what's the best (faster) choice to cycle continuously the values of a table: [code] while(..){ table[++i%MAX]; ... ...

  1. #1
    Registered User
    Join Date
    Oct 2003
    Posts
    106

    How much is %(modulus op.) heavy?

    Hello, I'm wondering what's the best (faster) choice to cycle continuously the values of a table:
    [code]
    while(..){
    table[++i%MAX];
    ...
    }
    [\code]
    or
    [code]
    while(..){
    table[++i];
    if(i==MAX)
    i=0;
    }
    [\code]

    Thanks for help.

  2. #2
    Registered User
    Join Date
    Oct 2003
    Posts
    106

    Ehm, I don't use tags so often..

    Here is the errata-corridge :P

    Hello, I'm wondering what's the best (faster) choice to cycle continuously the values of a table:
    Code:
    while(..){ 
    table[++i%MAX];
    ...
    }
    or
    Code:
    while(..){
    table[++i];
    if(i==MAX)
    i=0;
    }
    Thanks for help.

  3. #3
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    There is little point in worrying about that small of an "optimization". You're best served optimizing elsewhere. However, using % is the safer of the two, because in the second version, you increment i before doing whatever it is you're trying to do to your table, thus you'll end up running off the end. (Unless MAX is defined as "Array size -1", in which case, the first version will never reach the final cell in the array.)

    Quzah.
    Hope is the first step on the road to disappointment.

  4. #4
    Registered User
    Join Date
    Oct 2003
    Posts
    106
    Another difference that comes in my mind is about the type of i: in the first case (%) I should use a big size type (big enough to be able to contain the cycles number*MAX..) while using the second solution I could use a type big enough to contain the value MAX.
    BrownB

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Let the OP mark a thread solved
    By siavoshkc in forum A Brief History of Cprogramming.com
    Replies: 20
    Last Post: 07-20-2006, 12:16 PM
  2. NAQ: Everything you never wanted to know about CPP
    By evildave in forum C Programming
    Replies: 21
    Last Post: 12-12-2005, 09:56 AM
  3. searching problem
    By DaMenge in forum C Programming
    Replies: 9
    Last Post: 09-12-2005, 01:04 AM
  4. newbie needs advice!
    By bluenoser in forum C Programming
    Replies: 24
    Last Post: 10-16-2002, 07:28 PM
  5. Replies: 1
    Last Post: 11-19-2001, 03:45 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21