Действительно ли статические методы хороши для масштабируемости?

Прямо сейчас (по состоянию на 2008), все библиотеки SOAP, доступные для Python, сосут. Я рекомендую избежать SOAP, если это возможно. В прошлый раз мы, где вызвано для использования веб-сервиса SOAP из Python мы записали обертку в C#, который обработал SOAP на одной стороне и говорил COM прямо другой.

6
задан Silent Warrior 16 August 2009 в 16:40
поделиться

8 ответов

It depends on WHY the method is static. If it's static because it truly does not need context, then it will probably scale very well compared to something of similar complexity that is not static because it requires context.

However, if it is static merely because you cannot retain the needed context and must still pass it in, or because of some artificial goal of having more static methods, then I would suspect that it will actually scale LESS than the comparable method as non-static.

In fact I think that ASP Classic proved this point.

4
ответ дан 8 December 2019 в 04:09
поделиться

There are three problems to consider with static methods:

  1. You may introduce a bottleneck if your static method has a large critical region. The largest of course is to declare the whole method synchronized. If it can only be executing one at a time then it's a potential issue;
  2. Is whatever it's doing still consistent if you're running the same method in different VMs and on different machines? and
  3. Any method that relies on static methods has problems with unit testing.

It's not generally considered best practice but static helper methods are common. Too complex and another approach should probably be considered.

4
ответ дан 8 December 2019 в 04:09
поделиться

No static methods don't intrinsically scale better. Infact the programming style (imperative or object oriented) does not really make any difference to scaling whatsoever. There are two major aspects of scaling and what to do to improve scale depends on which we mean:

1 Scaling by number of requests a second handled

This type of scaling is normally about adding more computers to a cluster to improve overall throughput of the system. Increasing scaling is often about initially reducing the amount of shared resources used through the use of caches and then later making the data access split into shards.

2 Data Scaling

This is when the system gets more and more data over time and operations that access the data (search, filtering etc) get slower as the algorithms are more complex than O(1). In this case the normal strategy is to increase the number of read and write points and use parallel algorithms such as Map/Reduce.

But neither of these aspects has anything to do with whether you use static methods or not, just whether multiple requests work on large sets of data or single sources of data.

3
ответ дан 8 December 2019 в 04:09
поделиться

No. I think you may be assuming that each instance has its own copy of the method definition, taking up that amount of space for each instance, which is not the case.

Editing to add:

In case you wonder how an instance method can be actually shared between the instances: It is because each call to an instance method implicity passes a reference to the instance object to the method. This is generally referred to as the "implicit this" In other words - when you define or call an instance method with two parameters like myMethod(a, b), you can think of it as actually being myMethod(this, a, b), and Java takes care of the this parameter for you, without your having to explicitly define or pass it.

(This, by the way, is handled differently in Python, where you have to explicitly put the object reference in as the first parameter of an instance method definition, though not in the call.)

For an explanation of what goes on at the Java bytecode level here's a link: http://www.artima.com/underthehood/invocationP.html (См. Материал вокруг: «Ссылка на объект - это неявный указатель this, который передается любому методу экземпляра».)

2
ответ дан 8 December 2019 в 04:09
поделиться

Which form of scalability do you mean? The scalability, that the code is maintainable and extensible in big and small projects? Then using only static-methods hurt. Do you mean performance? If instance-methods are slower (what I don't believe in this generality), then this doesn't mean they don't scale. If they need twice the time as static-methods, they need also twice much time if you call them all 10000 times. Choosing the right algorithms and data-representation decide much more about the scalability of the performance.

At last, if you think static-methods are the way to go, you should not use an object-oriented language like Java. Try C or Pascal or classic Basic-dialects.

1
ответ дан 8 December 2019 в 04:09
поделиться

Does static methods and class are good для масштабируемости?

Одно мало общего с другим.

Я так думаю, что статический класс / метод улучшает масштабируемость приложения и методы экземпляра не масштабируются много.

Неправильно. Почему вы так думаете?

Хорошая практика программирования - напишите статический метод, где бы он ни был возможно?

Нет. Фактически, это очень плохая практика, поскольку она лишает возможности обслуживания преимуществ объектно-ориентированного программирования.

11
ответ дан 8 December 2019 в 04:09
поделиться

Я думаю, вы лаете не на то дерево:

В реальном мире масштабируемость (или ее отсутствие) обычно проистекает из соответствия алгоритмов и эффективности операций, выполняемых с хранилищами данных (подумайте: хорошие SQL-запросы).

Такие вещи, как статический метод или нет. (или процент статических методов) обычно не имеют ничего общего с масштабируемостью системы. Вы, безусловно, можете иметь супер-масштабируемую систему, которая не использует статические методы, или супер-масштабируемую систему, которая использует исключительно их.

1
ответ дан 8 December 2019 в 04:09
поделиться

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

0
ответ дан 8 December 2019 в 04:09
поделиться
Другие вопросы по тегам:

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