does order of members of objects of a class have any impact on performance?

前端 未结 3 1873
小蘑菇
小蘑菇 2021-02-05 12:44

May order of members in binary architecture of objects of a class somehow have an impact on performance of applications which use that class? and I\'m wondering about how to dec

3条回答
  •  名媛妹妹
    2021-02-05 13:07

    In addition to the runtime performance, described in the cache-line related answers, I think one should also consider memory performance, i.e. the size of the class object.

    Due to the padding, the size of the class object is dependent on the order of member variable declaration.

    The following declaration would probably take 12 bytes

    class foo {
        char c1;
        int  i;
        char c2;
    }
    

    However, upon simple re-ordering of the order of member declaration, the following would probably take 8 bytes

    class bar {
        int  i;
        char c1;
        char c2;
    }
    

    In machines aligned with 4-byte words:

    sizeof( foo ) = 12
    

    but

    sizeof( bar ) = 8
    

提交回复
热议问题