A
A
Anton_repr2020-06-04 12:49:58
C++ / C#
Anton_repr, 2020-06-04 12:49:58

Are static methods called faster?

The resharper often offers me to replace the usual method / with a static one. Today I learned that static methods are marked by the compiler as having non-virtual call sites, which prevents each method call from checking to see if the method pointer is null .
If static methods are called faster, then it's probably better to always mark class fields as static?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Roman, 2020-06-05
@Anton_repr

God forbid, where did you read such nonsense? First, there are no checks before calling the method, because the pointer to it, in principle, cannot be null, the address of the method is already known at the compilation stage. In IL, there are two instructions call and callvirt, the first is used to call static and non-virtual methods, the second is just to call virtual methods. Virtual methods are explicitly marked virtual. Calling a virtual method is more expensive, because before calling it is necessary to explicitly determine the type of the object and find the pointer to the method in its virtual method table, for a non-virtual method, the address of the method is already known at the compilation stage.
A static instance of a class is actually a different object, with different fields and methods.
I would recommend you, first, to demolish the resharper (I suspect you do not have a license for it), because it distracts more with its recommendations, the second is to learn sharp for a start, and then climb into the wilds of clr.
PS. Sat here in sharplab. It turns out that callvirt is also used to call instance methods. And most importantly, how it differs. Tests a pointer to an instance of a class, not a pointer to a method. But JIT optimizes the code so wildly that, for example, if there is an explicit object initialization and its use, then the checks are thrown out of the code, and even the function can be inlined. And the check consists of one processor instruction. Checking for null is done in the first method call, in the rest it is not, provided that the variable has not changed.

#
#, 2020-06-04
@mindtester

If static methods are called faster, then it's probably better to always mark class fields as static?
God forbid!!!
.. well, or all the same, figure it out for a start:
- everything that is static - one copy for the duration of one copy of the program
- see the paragraph above and turn on the brains

T
Timur Pokrovsky, 2020-06-04
@Makaroshka007

If you need a static field, then choose it.
If you have 10 user class objects, then of course the money field should not be static

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question