需要批评:在数组中存储对象

时间:2013-03-27 21:04:34

标签: java performance memory

为了提高我的java应用程序的性能,我正在考虑创建一个带有描述对象的静态final字段的类,然后放入从数组中检索该对象的所有数据的静态方法。

示例: 假设我想创建一个对象人: 假设一个人有年龄,身高,体重,眼睛的颜色和世界坐标。

通常我会做这样的事情:

  public class Person {
    private int age;
    private int height;
    private int weight;
    private int eyeR;
    private int eyeG;
    private int eyeB;
    private float x;
    private float y;
    private float z;
    //... getters and setters
  }

我想将这些人从客户端发送到服务器,所以我必须序列化对象并将它们发送到服务器,它将反序列化对象并复活另一端的人,现在我们都知道java对象存储在堆中,并且每个对象都具有分配用于描述对象的最小字节数。

我想做的是这样做: 创建一个描述对象人的类:

public class Person {
 // size contains the number of bytes to describe my person
 public static final int size; 
 //this byte here is used to identify a Person in a float array
 public static byte classID = 0;
 //these variables contains the position of my attributes inside a float array
 // since floats / int are all coded in 4 bytes
 public static final int age = 0;
 public static final int height = 1;
 public static final int eyeR = 2; 
 public static final int eyeG = 3;
 public static final int eyeB = 4;
 public static final int x = 5;
 public static final int y = 6;
 public static final int z = 7;

 //i don't check for nullity, i trust myself.
 public static int getAge(final float[] person) {
    return person[Person.age]; 
 }
 public static void setAge(final float[] person, float age) {
    return person[Person.age] = age; 
 }

 ... do the same thing for the rest also you can store 

}

我真的很想知道这个解决方案是否可行,因为我只使用浮点数组来存储我的人物数据,我可以在内存中获得数据的空间接近度,所以我想如果我访问数据我不会让任何页面遗漏。

我也不必序列化或反序列化我的对象,因为我的浮点数组很好,我只是使用我的静态方法来访问我的浮点数组。

1 个答案:

答案 0 :(得分:4)

  

现在我们都知道java对象存储在堆中,并且每个对象都分配了最少的字节来描述对象。

是的,这也适用于数组。

我无法看到您的代码节省了大量内存,但在我看来,它会使代码更难以阅读和维护。

真的,就是不要这样做。

  

因为我只使用浮点数组来存储我的人物数据,所以我可以在内存中获得数据的空间接近度,所以我想如果我访问数据我不会让任何页面遗漏。

对于Person实例中的所有数据,您也将具有空间接近度。这是另一个无益的好处。

相关问题