Можно использовать их для создания собственного linq поставщика для веб-сайта как Google или Flickr или Amazon, собственный сайт или другой поставщик данных.
Вы правы, методы существуют в памяти только один раз, они похожи на обычные функции с дополнительным скрытым параметром this.
И, конечно же, учитываются только элементы данных. распределение, ну, наследование может ввести некоторые дополнительные ptrs для vptrs в размере объекта, но это не имеет большого значения
You have already got some pretty good technical advice. I want to throw in something non-technical: As the STL showed us all, doing it all in member functions might not be the best way to do this. Rather than piling up arguments, I refer to Scott Meyers' class article on the subject: How Non-Member Functions Improve Encapsulation.
Although technically there should be no problem, you still might want to review your design from a design POV.
I suppose this is more of an answer than you're looking for, but here goes...
SO is filled with questions where people are worried about the performance of X, Y, or Z, and that worry is a form of guessing.
If you're worried about the performance of something, don't worry, find out.
Here's what to do:
Write the program
Learn from the experience
What this has taught me, and I've seen it over and over, is this:
Best practice says Don't optimize prematurely.
Best practice says Do use lots of data structure classes, with multiple layers of abstraction, and the best big-O algorithms, "information hiding", with event-driven and notification-style architecture.
Performance tuning reveals where the time is going, which is: Galloping generality, making mountains out of molehills, calling functions & properties with no realization of how long they take, and doing this over multiple layers using exponential time.
Then the question is asked: What is the reason behind the best practice for the big-O algorithms, the event- and notification-driven architecture, etc. The answer comes: Well, among other things, performance.
So in a way, best practice is telling us: optimize prematurely. Get the point? It says "don't worry about performance", and it says "worry about performance", and it causes the very thing we're trying unsuccessfully not to worry about. And the more we worry about it, against our better judgement, the worse it gets.
My constructive suggestion is this: Follow steps 1, 2, and 3 above. That will teach you how to use best practice in moderation, and that will give you the best all-around design.
Если вы действительно обеспокоены, вы можете указать своему компилятору встроить конструкторы. Этот шаг оптимизации должен дать вам чистый код и чистое выполнение.
Эти 2 бита кода идентичны:
Point x;
int l=x.getLength();
int l=GetLength(x);
, учитывая, что класс Point
имеет не виртуальный метод getLength (). Первый вызов фактически вызывает int getLength (Point & this)
, идентичную сигнатуре той, что мы написали во втором примере. (*)
Это, конечно, не применимо, если методы, которые вы вызываете, являются виртуальными, поскольку все будет проходить через дополнительный уровень косвенности (что-то вроде C-стиля int l = x-> lpvtbl-> getLength (x)
), не говоря уже о том, что вместо 2 int на каждый пиксель у вас будет 3, причем лишним будет указатель на виртуальную таблицу.
(*) this isn ' в точности верно, указатель this передается через один из регистров процессора, а не через стек,
I agree with the above comments wrt:performance and class layout, and would like to add a comment not yet stated about design.
It feels to me like you're over-using your Point class beyond it's real Design scope. Sure, it can be used that way but should it?
In past work in computer games I've often been faced by similar situations, and usually the best end result has been that when doing specialized processing (e.g. image processing) having a specialized code set for that which work on differently laid-out buffers has been more efficient.
This also allows you to performance optimize for the case that matters, in a more clean way, without making base code less maintainable.
In theory, I'm sure that there is a crafty way of using a complex combination of template code, concrete class design, etc., and getting nearly the same run-time efficiency ... but I am usually unwilling to make the complexity-of-implementation trade.
Первое: не оптимизируйте преждевременно. Во-вторых: чистый код легче поддерживать, чем оптимизированный.
В методах классов есть скрытый указатель this, но вам не стоит об этом беспокоиться. В большинстве случаев компилятор пытается передать его через регистр.
Наследование и виртуальная функция вводят косвенные ссылки в соответствующие вызовы (наследование = вызов конструктора / деструктора, виртуальная функция - каждый вызов этой функции).
Краткое:
Существует другое обсуждение классов, имеющих большие или маленькие интерфейсы (например, в одной из эффективных книг Скотта Мейерса (More) по C ++ - он выбирает минимальный интерфейс). Но это не имеет ничего общего с производительностью.
Функции-члены не копируются вместе с объектом. Только поля данных влияют на размер объекта.
Я создал тот же класс точек, что и вы, за исключением того, что это шаблонный класс и все функции встроены. Я ожидаю увидеть увеличение производительности, а не снижение этого. Однако изображение размером 800x600
будет иметь 480k
пикселей
, а его печать в памяти будет близка к 4M
без какой-либо информации о цвете. Не только память, но и инициализация объекта 480k
займет слишком много времени. Поэтому я думаю, что в таком случае это не лучшая идея. Однако, если вы используете этот класс для преобразования положения изображения или для графических примитивов (линий, кривых, кругов,