Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Storing array index vs storing class reference / struct value.

Discussion in 'Scripting' started by MathiasDG, Dec 19, 2014.

  1. MathiasDG

    MathiasDG

    Joined:
    Jul 1, 2014
    Posts:
    114
    Hello,

    I was wondering, is there any performance difference at all from doing this :
    Code (CSharp):
    1. public class Class1
    2. {
    3.     public Vertices[] vertices;
    4.     public Polygon[] polygons;
    5.  
    6.     public Class1()
    7.     {
    8.     }
    9.  
    10.     public struct Vertex
    11.     {
    12.         public float x;
    13.         public float y;
    14.     }
    15.  
    16.     public class Polygon
    17.     {
    18.         public Vertex[] vertices;
    19.     }
    20. }
    21.  
    to doing this ?

    Code (CSharp):
    1. public class Class1
    2. {
    3.     public Vertices[] vertices;
    4.     public Polygon[] polygons;
    5.  
    6.     public Class1()
    7.     {
    8.     }
    9.  
    10.     public struct Vertex
    11.     {
    12.         public float x;
    13.         public float y;
    14.     }
    15.  
    16.     public class Polygon
    17.     {
    18.         public int[] verticesID;   // And acess the vertices using their ID on the array.
    19.     }
    20. }
    21.  
    Using the first options seems a little more neat and easy to use, so i was just wondering if there were any reasons at all for using the second option?

    Vertices could also be a class, and there would be quite a lot of them.
    Polygons can share the same vertices of the array.

    Thanks!
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,514
    So technically... yes, there is a difference.

    The reason? Because Vertex is a struct that contains 2 floats in it.

    Structs are value types, and your struct is 64-bits in size. The structs in the array are not stored by reference, they are stored by value, so thusly the 'Polygon' class that stores an array of Vertex's will contain a duplicate of them, which mean that it'll be twice the size of an array of integers (which are only 32-bits).

    Memory usage is really the only difference in efficiency.

    If Vertex was a class, it would actually be just as efficient either way.

    Another issue is that because they're structs, the updates you may do to one, won't effect the other. So you'd end up having to update the values in both places.
     
    Jessy likes this.