Does accessing a single struct member pull the entire struct into the Cache?

前端 未结 1 828
闹比i
闹比i 2021-02-09 11:17

I\'ve been reading Ulrich Drepper\'s, \"What every programmer should know about memory\" and in section 3.3.2 Measurements of Cache Effects ( halfway down the page ) it gives me

相关标签:
1条回答
  • 2021-02-09 12:10

    The hardware does not know at all about the struct. But it is true that the hardware load in the cache some bytes around the bytes you are actually accessing. This is because the cache line has a size. It does not work on a byte by byte access but on e.g. 16 bytes size at a time.

    You have to be careful when ordering the members of the struct so that often used members are close to each other. For instance if you have the following struct:

    struct S {
      int foo;
      char name[64];
      int bar;
    };
    

    If the member variables foo and bar are used very often, the hardware will load in cache the bytes around foo, and when you'll access bar, it will have to load the bytes around bar. Even if these bytes around foo and around bar are never used. Now rewrite your struct as follows:

    struct S {
      int foo;
      int bar;
      char name[64];
    };
    

    When you'll use foo, the hardware will load in cache the bytes around foo. When you'll use bar, bar will already be in the cache because bar is contained in the bytes around foo. The CPU won't have to wait for bar to be in the cache.

    Answer is: accessing a single struct member does not pull the entire struct in the cache, but pull some other member of the struct into the cache.

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