java - 需要批评者 : store objects inside arrays

标签 java performance memory

<分区>

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

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

通常我会做这样的事情:

  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 对象存储在堆中,并且每个对象都分配了最少的字节来描述该对象。

我想做的是: 创建一个描述对象 person 的类:

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 

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

我也不必序列化或反序列化我的对象,因为我的 float 组本身就很好,我将只使用我的静态方法来访问我的 float 组。

最佳答案

now we all know that java objects are stored in the heap and that every object have a minimum of bytes that are allocated to describe the object.

是的,这也适用于数组。

我看不出您的代码节省了大量内存,但在我看来,这会使代码更难阅读和维护。

真的,只是不要这样做。

because since i am using only float arrays to store my person data, i can get spatial proximity of my data in the memory, so i guess if I access the data i wont make any page misses.

有了 Person 实例中的所有数据,您也将具有空间邻近性。这是另一个非 yield 。

关于java - 需要批评者 : store objects inside arrays,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15669442/

相关文章:

java - Spring Security 和 Tomcat 8 JSessionId 响应不匹配

java - JasperReports fillReport太慢且耗资源

java - Jersey 第一次与第二次等待响应的时间差异

performance - PostgreSQL 查询未执行或花费太多时间

c# - 什么时候为变量分配内存,是在声明时还是在初始化时?

css - 图像 Sprite 实际上比单独的图像更有效吗?

java - 处理dl查询中的数据值限制

java - Spring 和 Freemarker 的编码问题

java - VisualVM 没有反射(reflect)正确的元空间大小?

java - 实现 JSR-353 (JSON) 的 API 是什么