代码之家  ›  专栏  ›  技术社区  ›  Vignesh Gunasekaran

在对象数组上操作与在包含参数数组的单个对象上操作相比?

  •  0
  • Vignesh Gunasekaran  · 技术社区  · 6 年前

    我正在考虑建立一个路径查找系统,每个节点必须包含位置数据、与之相关的移动成本等等。哪种方法更有效,因为我的目标平台是移动设备。

    哪一个在性能方面更好?

    这是:

    public Class Test{
    int x;
    float y;
    string z;
    }
    
    .
    .
    .
    
    Test[] tests = new Test[100];
    
    for(int i=0; i< 100; ++i){
    tests[i].x = 0;
    tests[i].y = 0.5f;
    tests[i].z = "Hello:";
    }
    

    或者这个:

    public Class Test{
    int[] x;
    float[] y;
    string[] z;
    }
    
    .
    .
    .
    
    Test tests = new Test;
    test.x = new int[100];
    test.y = new float[100];
    test.z = new string[100];
    
    for(int i=0; i< 100; ++i){
    tests.x[i] = 0;
    tests.y[i] = 0.5f;
    tests.z[i] = "Hello:";
    }
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Bagdan Gilevich    6 年前

    在您的示例中,性能差异并不重要,但是第一个变量在代码可读性和灵活性方面更好。

    你可以用 struct 而不是 class 为了避免其他取消引用操作,它可能会提高性能。

        2
  •  1
  •   auslander    6 年前

    使用struct而不是class,它会给你性能,如果你想使用class多于second的话,性能比第一个高,我想是因为堆中有1个对象而不是100个对象