Code optimization about array iteration

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • zaeminkr@gmail.com

    #1

    Code optimization about array iteration

    Hello.

    I believed below two functions would have same performance.

    However, I realized the second form of array iteration are found more
    in many performance critical code like Microsoft CRT source code.

    Really the second form of array iteration(count _neg2) is faster?


    Thanks in advance.

    *************** *************** *************** *************** **************
    unsigned int count_neg1(int* int_array, unsigned int n)
    {
    unsigned int c = 0;
    unsigned int i = 0;

    while(i < n)
    {
    if(int_array[i++] < 0)
    {
    ++c;
    }
    }

    return c;
    }
    *************** *************** *************** *************** **************
    unsigned int count_neg2(int* int_array, unsigned int n)
    {
    unsigned int c = 0;
    int* end = int_array + n;

    while(int_array < end)
    {
    if(*int_array++ < 0)
    {
    ++c;
    }
    }

    return c;
    }

  • Keith Thompson

    #2
    Re: Code optimization about array iteration

    zaeminkr@gmail. com writes:
    I believed below two functions would have same performance.
    >
    However, I realized the second form of array iteration are found more
    in many performance critical code like Microsoft CRT source code.
    >
    Really the second form of array iteration(count _neg2) is faster?
    >
    >
    Thanks in advance.
    >
    *************** *************** *************** *************** **************
    unsigned int count_neg1(int* int_array, unsigned int n)
    {
    unsigned int c = 0;
    unsigned int i = 0;
    >
    while(i < n)
    {
    if(int_array[i++] < 0)
    {
    ++c;
    }
    }
    >
    return c;
    }
    *************** *************** *************** *************** **************
    unsigned int count_neg2(int* int_array, unsigned int n)
    {
    unsigned int c = 0;
    int* end = int_array + n;
    >
    while(int_array < end)
    {
    if(*int_array++ < 0)
    {
    ++c;
    }
    }
    >
    return c;
    }
    The comp.lang.c FAQ is at <http://www.c-faq.com/>. You've asked
    question 20.14.

    --
    Keith Thompson (The_Other_Keit h) kst-u@mib.org <http://www.ghoti.net/~kst>
    San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
    "We must do something. This is something. Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"

    Comment

    Working...