反射字段动态get,内存申请/浪费
1. get() 会自动创建封装类对象,导致内存浪费
2. 使用基本getInt()方法,直接返回基础类型,内存使用低
使用反射字段,get动态获取字段值,测试内存申请情况
public static class C1 {
private int i1;
public int getI1() {
return i1;
}
public void setI1(int i1) {
this.i1 = i1;
}
}
@Test
public void relectionTest1() throws IllegalAccessException, NoSuchFieldException {
C1 c = new C1();
c.setI1(123456383);
Field f = C1.class.getDeclaredField("i1");
f.setAccessible(true);
int s = 0;
long n = 10000000000l;
for (long j = 0; j < n; j++) {
for (long i = 0; i < n; i++) {
Object i11 = f.get(c);
int i1 = (int) i11;
// int i1 = f.getInt(c);
s += i1;
}
}
System.out.println("test n:" + n + ", s:" + s);
}
1. get() 会自动创建封装类对象,导致内存浪费
增量内存全部由main主线程分配
2. 使用基本getInt()方法,直接返回基础类型,内存使用低
for (long j = 0; j < n; j++) {
for (long i = 0; i < n; i++) {
// Object i11 = f.get(c);
// int i1 = (int) i11;
int i1 = f.getInt(c);
s += i1;
}
}
main线程没有申请内存,即getInt不会动态申请内存