How to avoid multiplication in pointer arithmetic?

后端 未结 1 1754
悲&欢浪女
悲&欢浪女 2021-01-13 13:06

If I write

int main(int argc, char *argv[])
{
    int temp[50][3];
    return &temp[argc] - &temp[0];
}

and compile it with Visual C+

相关标签:
1条回答
  • 2021-01-13 14:05

    Why am I getting an imul instruction here instead of just bit shifts, etc.?

    The multiplication is to divide by 3 (the size of each inner array), using the fact that 0x2AAAAAAB is 231/3. You can't do that with a small number of shifts and adds; multiplication really is the fastest option.

    I'm suspecting imul is killing its performance.

    On most modern platforms, integer multiplication is usually as fast as simpler operations, so it may be the fastest option even when it could be replaced by a couple of shifts and adds. When you have performance issues, always measure to find the real bottlenecks; they're often in the places you least suspect.

    Is there a good way to prevent it in general and instead replace it with cheaper operations?

    On platforms where multiplication really is expensive: avoid arrays of awkwardly sized data structures; and avoid subtracting pointers, since that requires division by the object size.

    0 讨论(0)
提交回复
热议问题