类中成员的最佳顺序是什么? [英] What is the optimal order of members in a class?

查看:86
本文介绍了类中成员的最佳顺序是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下课程:

class Example
{
  bool m_b1;
  SomeClass m_sc;  
  bool m_b2;
  char * m_name;
  bool m_b3;
  int m_i1;
  SomeClass * m_sc;
  int m_i2;
};

成员的最佳顺序是什么?据我所知,在创建此类的实例时,成员声明的顺序等于内存中成员的顺序.

What is the optimal order of members? As far as I know, the order of declaration of members equals the order of members in memory, when creating an instance of this class.

  • 我应该对成员进行排序,以使相等的类型在一起吗?
  • 所有指针是否都属于同一类型?
  • 重排对物体的尺寸有影响吗? 4或8字节对齐在这里适用吗?
  • 如何查看上述效果? sizeof是否显示对象使用的内存(包括用于对齐的空白空间)?
  • 一天结束时对成员进行排序是否更好,以便他们的含义和上下文更容易理解?

推荐答案

通常,您应该按大小排序,从大到小.这将创建结构的最小填充,从而最小化结构尺寸.如果在连续分配的内存中使用结构对象,例如向量,并且对缓存有很大帮助(更多对象可以容纳在同一缓存行中).

As a rule of thumb you should order by size, greater to smaller. This will create the minimum padding of the structure, thus minimizing the structure size. This matters most if objects of the structure are used in a contiguous allocated memory, e.g. vector and helps a lot with cache (more objects fit in the same cache line).

安德烈·亚历山德斯库(Andrei Alexandrescu)(我认为是CppCon之一)展示的另一个令人惊讶的优化方法是,他首先带来了访问量最大的成员.因为偏移为零,所以速度更快.当然,在对应用程序进行基准测试并关注性能的每一个小细节之后,他谈论的是微优化.

Another surprising optimization demonstrated by Andrei Alexandrescu (I think was in one of CppCon) is that he brought the most accessed member first. This is faster because the offset is zero. Of course he was talking about micro-optimization, after benchmarking the hell out of the application and caring for every little strop of performance.

这篇关于类中成员的最佳顺序是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆