Статические участники помогают эффективности памяти?

Мы закончили тем, что использовали Сетка Сигмы ... спасибо за все другие ответы!

17
задан Hanno Fietz 30 September 2009 в 07:45
поделиться

4 ответа

Единственное различие между статическими методами и нестатическими (экземпляровыми) методами за кулисами заключается в том, что дополнительный скрытый параметр ( this ) передается методам экземпляра и что методы экземпляра могут быть вызваны с использованием косвенной отправки (если виртуальная). Дополнительного места для кода не требуется.

Редактировать:


Мой ответ сосредоточен на методах, но при более внимательном чтении я вижу, что вопрос больше касается статических данных. Да, статические данные в некотором смысле экономят память, так как их всего одна копия. Конечно, должны ли данные быть статичными, больше зависит от значения или использования данных, а не от экономии памяти.

Если вам нужно иметь большое количество объектов и вы хотите сохранить память, вы можете захотеть также выясните, применимо ли использование шаблона «Легковес» .

20
ответ дан 30 November 2019 в 11:04
поделиться

The decision shouldn't be made on the grounds of efficiency - it should be made on the grounds of correctness.

If your variable represents a distinct value for each instance, it should be an instance variable.

If your variable is a common value associated with the type rather than an individual instance of the type, it should be a static variable.

You're correct, however - if you have a static variable, you won't "pay" for that with every instance. That just adds an extra reason to make variables static where they don't represent part of the state of the object.

When you mention methods in your question, are you talking about local variables? You'll get a new set of local variables for every method call - including recursive calls. However, this doesn't create a new set of static or instance variables.

17
ответ дан 30 November 2019 в 11:04
поделиться

Простой ответ - да. Создание экземпляра каждый раз, когда нет ничего равного воссозданию всего объекта, статические методы и переменные обычно потребляют меньше памяти в зависимости от того, как они используются. Конечно, если вам нужно создать только один экземпляр для всей программы, разницы нет. И помните, что вы всегда можете передавать экземпляры в качестве ссылок, где у вас не может быть статических объектов, и вам нужно их повторно использовать.

4
ответ дан 30 November 2019 в 11:04
поделиться

If you make a member variable static, you save memory per-instance (assuming there's more than one instance), but the real gain is that you don't have to work at keeping all those non-static members consistent with each other, and you don't need a current instance in order to access the static member.

If you make a method static, you save a few bytes on the stack for each nested call (there's no implicit 'this' parameter), but that's only relevant if you're doing very heavy recursion. Of course if the function needs to know which instance you're dealing with, you'll need an explicit parameter to replace the implicit 'this' anyway, so you gain nothing.

There is no per-instance cost to having a static method, or for that matter, a non-static method. The costs occur on calls.

The real reason to use a static method is because there is no instance - at least when you call the method. For example, you might use a static method to create and initialise instances (one of the "factory" design patterns), or to reference a singleton instance.

4
ответ дан 30 November 2019 в 11:04
поделиться
Другие вопросы по тегам:

Похожие вопросы: