C ++:BIG类的性能影响(有很多代码) [英] C++: Performance impact of BIG classes (with a lot of code)

查看:137
本文介绍了C ++:BIG类的性能影响(有很多代码)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



如果我有例如,一个类 Point ,只有 uint x; uint y; 作为数据,并且已经定义了数学可以对点作为方法的几乎所有内容。这些方法中的一些可能是巨大的。 (copy-)构造函数只做初始化两个数据成员。

  class Point 
{
int mx; int my;
Point(int x,int y):mx(x),my(y){};
Point(const Point& other):mx(other.x),my(other.y){};
// ....大量方法....
};

现在。我加载一个大图片,并为每个像素创建一个,将em放入向量中并使用。 (例如,所有方法都被调用一次)
这只是一个愚蠢的例子!



有很多实用功能吗?我不是以任何方式谈论虚拟函数!



我的动机为此:我经常发现自己写的漂亮和相对强大的类,但是当我必须初始化/使用一吨他们喜欢在上面的例子,我紧张。
我想我不应该。



我认为我知道的是:


  1. 方法在内存中只存在一次。
    (优化除外)

  2. 分配
    仅对数据
    成员进行,它们是
    复制的唯一东西。 li>

所以没关系。我错过了什么?

解决方案

你是对的,方法只存在一次在内存中,额外隐藏这个参数。



当然,只有数据成员被考虑分配,好的,继承可能会引入对象大小的vptrs的一些额外的ptrs,不是大事


I wonder if and how writing "almighty" classes in c++ actually impacts performance.

If I have for example, a class Point, with only uint x; uint y; as data, and have defined virtually everything that math can do to a point as methods. Some of those methods might be huge. (copy-)constructors do nothing more than initializing the two data members.

class Point
{
   int mx; int my;
   Point(int x, int y):mx(x),my(y){};
   Point(const Point& other):mx(other.x),my(other.y){};
 // .... HUGE number of methods....
};

Now. I load a big image and create a Point for every pixel, stuff em into a vector and use them. (say, all methods get called once) This is only meant as a stupid example!

Would it be any slower than the same class without the methods but with a lot of utility functions? I am not talking about virtual functions in any way!

My Motivation for this: I often find myself writing nice and relatively powerful classes, but when I have to initialize/use a ton of them like in the example above, I get nervous. I think I shouldn't.

what I think I know is:

  1. Methods exist only once in memory. (optimizations aside)
  2. Allocation only takes place for the data members, and they are the only thing copied.

So it shouldn't matter. Am I missing something?

解决方案

You are right, methods only exist once in memory, they're just like normal functions with an extra hidden this parameter.

And of course, only data members are taken in account for allocation, well, inheritance may introduce some extra ptrs for vptrs in the object size, but not a big deal

这篇关于C ++:BIG类的性能影响(有很多代码)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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