What are the differences between using array offsets vs pointer incrementation?

后端 未结 11 1336
醉话见心
醉话见心 2021-02-06 13:39

Given 2 functions, which should be faster, if there is any difference at all? Assume that the input data is very large

void iterate1(const char* pIn, int Size)
{         


        
11条回答
  •  北恋
    北恋 (楼主)
    2021-02-06 14:21

    The pointer op used to be much faster. Now it's a bit faster, but the compiler may optimize it for you

    Historically it was much faster to iterate via *p++ than p[i]; that was part of the motivation for having pointers in the language.

    Plus, p[i] often requires a slower multiply op or at least a shift, so the optimization of replacing multiplies in a loop with adds to a pointer was sufficiently important to have a specific name: strength reduction. The subscript also tended to produce bigger code.

    However, two things have changed: one is that compilers are much more sophisticated and are generally capable of doing this optimization for you.

    The other is that the relative difference between an op and a memory access has increased. When *p++ was invented memory and cpu op times were similar. Today, a random desktop machine can do 3 billion integer ops / second, but only about 10 or 20 million random DRAM reads. Cache accesses are faster, and the system will prefetch and stream sequential memory accesses as you step through an array, but it still costs a lot to hit memory, and a bit of subscript fiddling isn't such a big deal.

提交回复
热议问题