Programing

정적 메서드와 인스턴스 메서드의 성능

lottogame 2020. 8. 16. 21:49
반응형

정적 메서드와 인스턴스 메서드의 성능


내 질문은 정적 메서드 대 인스턴스 메서드의 성능 특성 및 확장 성과 관련이 있습니다. 이 시나리오에서는 모든 클래스 정의가 단일 어셈블리에 있고 여러 개의 개별 포인터 형식이 필요하다고 가정합니다.

치다:

public sealed class InstanceClass
{
      public int DoOperation1(string input)
      {
          // Some operation.
      }

      public int DoOperation2(string input)
      {
          // Some operation.
      }

      // … more instance methods.
}

public static class StaticClass
{
      public static int DoOperation1(string input)
      {
          // Some operation.
      }

      public static int DoOperation2(string input)
      {
          // Some operation.
      }

      // … more static methods.
}

위의 클래스는 도우미 스타일 패턴을 나타냅니다.

인스턴스 클래스에서 인스턴스 메서드를 해결하는 데는 StaticClass와 달리 시간이 걸립니다.

내 질문은 다음과 같습니다.

  1. 상태를 유지하는 것이 문제가되지 않을 때 (필드 나 속성이 필요하지 않음) 항상 정적 클래스를 사용하는 것이 더 낫습니까?

  2. 이러한 정적 클래스 정의가 상당수있는 경우 (예 : 각각 여러 정적 메서드가있는 100 개) 동일한 수의 인스턴스 클래스 정의에 비해 실행 성능이나 메모리 소비에 부정적인 영향을 미칩니 까?

  3. 동일한 인스턴스 클래스 내의 다른 메서드가 호출 될 때 인스턴스 확인이 계속 발생합니까? 예를 들어 동일한 인스턴스 this.DoOperation2("abc")내에서 와 같이 [this] 키워드를 사용합니다 DoOperation1.


이론적으로 정적 메서드는 추가 숨겨진 this매개 변수로 인해 인스턴스 메서드보다 약간 더 나은 성능을 발휘해야합니다 .

실제로 이것은 다양한 컴파일러 결정의 소음에 숨겨 질 정도로 거의 차이가 없습니다. (따라서 두 사람이 다른 사람보다 더 나은 결과를 "증명"할 수 있습니다.) 특히 this는 일반적으로 레지스터에서 전달되고 종종 해당 레지스터에서 시작되기 때문입니다.

이 마지막 요점은 이론적으로 객체를 매개 변수로 사용하고 동일한 객체의 인스턴스와 동등한 것보다 약간 덜 좋은 작업을 수행하는 정적 메서드를 예상해야 함을 의미합니다. 다시 말하지만, 차이가 너무 작아서 측정을 시도하면 다른 컴파일러 결정을 측정하게 될 것입니다. (특히 해당 참조가 레지스터에 있으면 전체 시간이 매우 높기 때문에).

실제 성능 차이는 자연스럽게 정적 인 작업을 수행하기 위해 메모리에 객체를 인위적으로 넣었는지, 아니면 자연스럽게 인스턴스가되어야하는 작업을 수행하기 위해 복잡한 방식으로 객체 전달 체인을 엉키고 있는지 여부에 달려 있습니다.

따라서 1 번입니다. 상태를 유지하는 것이 문제가되지 않을 때는 항상 정적 인 것이 낫습니다. 왜냐하면 그것이 정적 인 것이기 때문입니다 . 성능 문제는 아니지만 컴파일러 최적화를 훌륭하게 수행하는 전체적인 규칙이 있습니다. 누군가 이상하게 사용되는 경우보다 정상적인 사용으로 나타나는 경우를 최적화하려고 노력했을 가능성이 높습니다.

번호 2. 차이가 없습니다. 메타 데이터의 양, 실제 DLL 또는 EXE 파일에 얼마나 많은 코드가 있는지, 얼마나 많은 jitted 코드가 있는지에 따라 각 멤버에 대해 클래스 당 비용이 일정합니다. 이것은 인스턴스이든 정적이든 동일합니다.

항목 3 this도 마찬가지 this입니다. 그러나 참고 :

  1. The this parameter is passed in a particular register. When calling an instance method within the same class, it'll likely be in that register already (unless it was stashed and the register used for some reason) and hence there is no action required to set the this to what it needs to be set to. This applies to a certain extent to e.g. the first two parameters to the method being the first two parameters of a call it makes.

  2. Since it'll be clear that this isn't null, this may be used to optimise calls in some cases.

  3. Since it'll be clear that this isn't null, this may make inlined method calls more efficient again, as the code produced to fake the method call can omit some null-checks it might need anyway.

  4. That said, null checks are cheap!

It is worth noting that generic static methods acting on an object, rather than instance methods, can reduce some of the costs discussed at http://joeduffyblog.com/2011/10/23/on-generics-and-some-of-the-associated-overheads/ in the case where that given static isn't called for a given type. As he puts it "As an aside, it turns out that extension methods are a great way to make generic abstractions more pay-for-play."

However, note that this relates only to the instantiation of other types used by the method, that don't otherwise exist. As such, it really doesn't apply to a lot of cases (some other instance method used that type, some other code somewhere else used that type).

Summary:

  1. Mostly the performance costs of instance vs static are below negligible.
  2. What costs there are will generally come where you abuse static for instance or vice-versa. If you don't make it part of your decision between static and instance, you are more likely to get the correct result.
  3. There are rare cases where static generic methods in another type result in fewer types being created, than instance generic methods, that can make it sometimes have a small benefit to turn rarely used (and "rarely" refers to which types it's used with in the lifetime of the application, not how often it's called). Once you get what he's talking about in that article you'll see that it's 100% irrelevant to most static-vs-instance decisions anyway. Edit: And it mostly only has that cost with ngen, not with jitted code.

Edit: A note on just how cheap null-checks are (which I claimed above). Most null-checks in .NET don't check for null at all, rather they continue what they were going to do with the assumption that it'll work, and if a access exception happens it gets turned into a NullReferenceException. As such, mostly when conceptually the C# code involves a null-check because it's accessing an instance member, the cost if it succeeds is actually zero. An exception would be some inlined calls, (because they want to behave as if they called an instance member) and they just hit a field to trigger the same behaviour, so they are also very cheap, and they can still often be left out anyway (e.g. if the first step in the method involved accessing a field as it was).


When keeping state is not a concern (no fields or properties are required), is it always better to use a static class?

I would say, yes. As declaring something static you declare an intent of stateless execution (it's not mandatory, but an intent of something one would expect)

Where there is a considerable number of these static classes (say 100 for instance, with a number of static methods each) will this affect execution performance or memory consumption negatively as compared with the same number of instance classes?

Don't think so, unless you're sure that static classes are really stetless, cause if not it's easy mess up memory allocations and get memory leaks.

When the [this] keyword is used to call another method within the same instance class, does the instance resolution still occur?

Not sure, about this point (this is a purely implementation detail of CLR), but think yes.


static methods are faster but less OOP, if you'll be use design patterns static method likely bad code, to write business logic better without static, common functions like file reading, WebRequest etc better realize as static... you questions have no universal answer

참고URL : https://stackoverflow.com/questions/12279438/performance-of-static-methods-vs-instance-methods

반응형