Passing by ref in C# - why is it slower?

Code profiling for .NET Developers

Moderators: Luke Jefferson, StephenC, Alex.Davies, AndrewH, melvyn.harbour, Laura Morley

Passing by ref in C# - why is it slower?

Postby simon.carter » Tue Dec 21, 2010 10:57 am

Please redirect me if this is the wrong place for this kind of post as this isn't really an ANTS issue, just something we've found by using ANTS.

I'm finding that passing some objects, especially smaller ones, by reference is up to 20% slower than making a copy. Sometimes passing by ref is up to 20% faster. I'd assumed from my c++ background that this would normally be true. What's going on? Is there any way to predict when using ref will be faster? Looking at the disassembly isn't necessarily that helpful as it doesn't explain why the code has been compiled that way.
simon.carter
 
Posts: 6
Joined: Tue Dec 21, 2010 10:49 am

Postby melvyn.harbour » Tue Dec 21, 2010 11:53 am

Just to try and clarify what you're doing, you say you're passing an object by reference. Since you're talking about an object, which is a reference type, you're always going to be passing it by reference - you don't really get a choice in that!

Could you post some sample code to show what you're doing?

Mel
Melvyn Harbour
Project Manager
.NET Tools Division
melvyn.harbour
 
Posts: 27
Joined: Mon Mar 15, 2010 3:27 pm

Postby simon.carter » Tue Dec 21, 2010 12:28 pm

My apologies - I should have said passing a value type by reference.
Code: Select all
struct MyValueType
{
    int _Value1;
    int _Value2;
}

class MyClass
{
    public MyMethodByRef(ref MyValueType A)
    {
        ...
    }

    public MyMethodCopy(MyValueType A)
    {
        ...
    }
}




MyMethodByRef is often slower.
simon.carter
 
Posts: 6
Joined: Tue Dec 21, 2010 10:49 am

Postby melvyn.harbour » Tue Dec 21, 2010 2:59 pm

From the quick tests I'm doing here, it would appear that it's almost all down to which method is encountered first. The first one to be encountered requires the JIT to look at the whole class.

Mel
Melvyn Harbour
Project Manager
.NET Tools Division
melvyn.harbour
 
Posts: 27
Joined: Mon Mar 15, 2010 3:27 pm

Postby simon.carter » Tue Dec 21, 2010 3:36 pm

Thanks for looking, though I'd be surprised if that were the full story - I'm executing these methods many many thousands of times and the JIT overhead should be lost in the noise. And I thought ANTS made it clear which parts of the timing were JIT overhead?

The main thing is that ANTS gives me the results I need, so cheers.

Simon
simon.carter
 
Posts: 6
Joined: Tue Dec 21, 2010 10:49 am


Return to ANTS Performance Profiler 6

Who is online

Users browsing this forum: No registered users and 1 guest