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

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.

Comments

  • MelHarbourMelHarbour Cambridge, United Kingdom Posts: 29 Bronze 1
    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
  • My apologies - I should have said passing a value type by reference.
    struct MyValueType
    {
        int _Value1;
        int _Value2;
    }
    
    class MyClass
    {
        public MyMethodByRef(ref MyValueType A)
        {
            ...
        }
    
        public MyMethodCopy(MyValueType A)
        {
            ...
        }
    }
    
    
    

    MyMethodByRef is often slower.
  • MelHarbourMelHarbour Cambridge, United Kingdom Posts: 29 Bronze 1
    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
  • 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
Sign In or Register to comment.