Is accessing statically or dynamically allocated memory faster?

后端 未结 5 844
无人及你
无人及你 2021-01-07 23:27

There are 2 ways of allocating global array in C:

  1. statically

    char data[65536];
    
  2. dynamically

    char *d         
    
    
            
5条回答
  •  [愿得一人]
    2021-01-08 00:01

    I think that data locality is much more of an issue than computing the base address of the array. (I could imagine cases where accessing the pointer contents is extremely fast because it is in a register while the offset to the stack pointer or text segment is a compile time constant; accessing a register may be faster.)

    But the real issue will be data locality, which is often a reason to be careful with dynamic memory in performance critical tight loops. If you have more dynamically allocated data which happens to be close to your array, chances are the memory will remain in the cache. If you have data scattered all over the RAM allocated at different times, you may have many cache misses accessing them. In that case it would be better to allocate them statically (or on the stack) next to each other, if possible.

提交回复
热议问题