Zerowalker
Zerowalker

Reputation: 767

Using Classes Static, slower than using it immediately?

I noticed that if I use a code from a static class, it´s slower than if I run it directly where I want it.

For example:

static class FastMethods
{
    public static byte[] GetBytes(int index, long value)
    {
        byte[] target = new byte[sizeof(Int32)];
        target[index++] = (byte)value;
        target[index++] = (byte)(value >> 8);
        target[index++] = (byte)(value >> 16);
        target[index] = (byte)(value >> 24);
        return target;
    }
}

There is the code I want to use in a separate class, so I can have it more organized. Now this is slower than if I do this:

int index = 0;
long value = ms.Length;
byte[] target = new byte[sizeof(Int32)];
target[index++] = (byte)value;
target[index++] = (byte)(value >> 8);
target[index++] = (byte)(value >> 16);
target[index] = (byte)(value >> 24);

Both do the exact same thing, using the same numbers. If I use the static class, I will just write something like:

var target = FastMethods.GetBytes(0,ms.Length);

So, if I am not completely lost, it should be doing the same thing at least.

And now, when I say slower, I don´t mean a lot, I am talking about ticks. From 1-3 ticks to 3-4.

It normally is at 1-2, and Static will be at around 3, not reaching 1 from my short tests at least.

Upvotes: 1

Views: 159

Answers (2)

Ehsan
Ehsan

Reputation: 32671

So, if i am not completely lost, it should be doing the same thing at least.

It is doing the same thing as far as fetching of values is concerned, but behind the scenes a lot more is going on. As calling the method has it's own overhead.

But it is never a lot and it is a very small compromise that you have to make for well organised code.

Upvotes: 2

CallumDev
CallumDev

Reputation: 239

Method calls always have a slight overhead when compared to inline code as there are context changes that are made when a method is called. More IL instructions are generated (pushing arguments, call instruction) than with inline code but the performance loss is very negligible.

Upvotes: 2

Related Questions