Is ref and out faster??

  • Thread starter Thread starter ozgur develioglu
  • Start date Start date
O

ozgur develioglu

Hi everyone,

In C language passing variables as pointers to functions is much more
faster then passing the original variables (Because you copy only the
pointer of the variable to the stack, not the whole variable).
Is this also true for C#, if you use ref or out for your parameter
instead of passing the whole variable.

Thanks.
 
University teachers still advice to use pointers and break your note in the
exam if you don't do this. Thanks for the help.
Ozgur.
 
Well, in C++ it is appropriate to use pointers, C# kindof does it
automatically.
That is, the C++ syntax for the following is very similar to the
corresponding C# syntax:
(C++) MyClass *p = new MyClass ();
(C#) MyClass p = new MyClass ();
In both cases, they are both heap-based objects, and p holds a reference to
that object on the heap.

NOW, I need a C++ guru to help me out (I believe that Method1 from C++ is
pretty much the same as Method1 from C#, and the same for Method2. Anybody
care to comment?)

There are two ways to pass the above variable p in C++:
Method1: (pass a pointer, by value)
(C++) WorkWithObject(MyClass *myObject) { myObject->ClassMethod(); }
(C++) WorkWithObject(p);
Method2: (pass by reference)
(C++) WorkWithObject(MyClass &myObject) { myObject.ClassMethod(); }
(C++) WorkWithObject(*p);

Which are very similar (I believe) to the following two C# methods:
Method1: (pass by value)
(C#) WorkWithObject(MyClass myObject) { myObject.ClassMethod(); }
(C#) WorkWithObject(p);
Method2: (pass by reference)
(C#) WorkWithObject(ref MyClass myObject) { myObject = new MyClass() }
(C#) WorkWithObject(ref p);

I don't think these are 100% the same. It's funny that I believe in C++,
the pass by reference is often preferred. In C#, pass by value is FAR
preferred (to the extent that using ref is strongly discouraged, unless you
REALLY need it).
 
My understanding is this. Method 2 in C++ is equivalent (more or less) to
Method 2 in C#.

There isn't really an equivalent to C++ 1. Sure, the value you're passing is
the pointer to the object, instead of the object itself, which makes it seem
the same as C# passing the reference. But with that pointer in C++, you
could do all the tricky pointer arithmetic which you can't do with the
reference in C#. As you can't take a pointer to a managed type in unsafe C#
code, there's no full equivalent to C++1 in C#.

I think the closest equivalent of C#1 in C++ would be WorkWithObject(const
MyClass &myObject).

It's been a while since I've done much C++ :P

Niall
 
Back
Top