- Home /
Mesh return vs out Mesh
is it better to use:
Mesh mesh = Mesh GenerateMesh(){ ... }
or
void GenerateMesh(out mesh)
ie get an output or pass in the mesh
the answers below are conflicting... memory leak vs efficiency...
Performance-wise, this is generally needless micro-optimization. You are unlikely to be in a position where the difference matters. You really should consider code design and structure over saving a nanosecond. return
is almost always the simplest straight-forward case, and out
has no benefits when using a single output.
I'm not sure where the "memory leak" comment is co$$anonymous$$g from. You can make memory leak regardless if you do it with out
or return
. Objects don't leak unless you go out of your way to find a way to do it. The return
example does not make a $$anonymous$$esh
leak and I have no idea why they would think it does. This is like the most common syntax for functions returning object instances and I would think someone would have noticed if it leaked memory!
Answer by Acegikmo · Feb 24, 2014 at 06:34 PM
I would guess it's more efficient and safe to use out or ref. If the variable mesh is already referring to a mesh object, the first example will them make a new mesh, and then assign it to the mesh variable, and thus there's a potential risk of object leaking. If you're using out, you can directly modify the existing one.
Answer by RudyTheDev · Feb 24, 2014 at 06:50 PM
It's almost always simpler to use return
unless you have a specific use-case scenario. out
is when you need 2+ returned variables and out
for a single variable just complicates code. And ref
is essentially for not copying value types and passing references/pointers (and Mesh
isn't a value type, so it just "double-references" with no benefit). There is no performance benefit to using out
(see comment). In fact, MSDN recommends not using out
/ref
.
Ran a quick performance test:
for (int i = 0; i < 10000000; i++)
a = $$anonymous$$ake$$anonymous$$eHello_Return(); // 361 ms (31 ms on empty for)
private Hello $$anonymous$$ake$$anonymous$$eHello_Return()
{
return new Hello(3);
}
versus
for (int i = 0; i < 10000000; i++)
$$anonymous$$ake$$anonymous$$eHello_Out(out a); // 582 ms
private void $$anonymous$$ake$$anonymous$$eHello_Out(out Hello hello)
{
hello = new Hello(3);
}
on a dummy class
public class Hello
{
private int a;
public Hello(int givenA) { a = givenA; }
}
Your answer
Follow this Question
Related Questions
Procedural array of meshes problem / solved 1 Answer
Do I need to split my mesh up to properly UV texture it? 1 Answer
Trouble with Inaccurate Mesh Collider 0 Answers
How to subdivide a single face on a mesh? 0 Answers
Multiple Cars not working 1 Answer