1

问题

在基于服务器的 java 解决方案中,我们需要一个更大的带有静态值的查找表(大约 300 kB,但数据每年都在增加,明年会有新的值)。

通常表会放在数据库中,但我们现在讨论在 Java 类中以 Java 代码的形式实现它。我将只使用一个计算表值的成员函数对类进行编程。不需要对象实例或其他内存 - 只需代码。

编码表

public class Lookup {

 public static float getValue (int year, int c1, int c2, int c3) {
    if (year == 2012) {
       if (c1 == 1) { // about 70 kByte of code
             ....
            return 7.34;
       }
    }
    if (year == 2013) { // about 70 kByte of code
       if (c1 == 1) {
         ....
            return 8.23;
    }
  }

}

我的问题

该表逐年增加,很少使用较旧的年份。每年实现一个函数而不是一个将年份作为参数的函数会是一个优势吗?每年实施一门课程会是一个优势吗?JVM 会检测到没有使用较早的年份并释放内存吗?

每年的特殊功能

这是否更好?更灵活的内存消耗?

public class Lookup {

  public static float getValue (int year, int c1, int c2, int c3) {
    if (year == 2012) return Lookup.getValue2012 (c1, c2, c3);
    if (year == 2013) return Lookup.getValue2012 (c1, c2, c3);
  }

  public static float getValue2012 (int year, int c1, int c2, int c3) {
    if (c1==1) { // about 70 kByte of code
             ....
            return 7.34;
    }
  }
  public static float getValue2013 (int year, int c1, int c2, int c3) {
    if (c1==1) { // about 70 kByte of code
             ....
            return 8.23;
    }
 }
}

每年的特殊课程

还是这样更好?更灵活的内存使用?

public class Lookup {

  public static float getValue (int year, int c1, int c2, int c3) {
    if (year == 2012) return Lookup2012.getValue (c1, c2, c3);
    if (year == 2013) return Lookup2013.getValue (c1, c2, c3);
  }

}
public class Lookup2012 {

  public static float getValue (int year, int c1, int c2, int c3) {
    if (c1==1) { // about 70 kByte of code
             ....
            return 7.34;
    }
  }
}

public class Lookup2013 {

  public static float getValue (int year, int c1, int c2, int c3) {
    if (c1==1) { // about 70 kByte of code
             ....
            return 8.23;
    }
 }
}
4

1 回答 1

0

要回答您的问题,我认为在类之间拆分静态方法或将它们放在同一个类中没有任何区别。原因是,无论它们在哪里声明,静态方法都只会在类加载器启动期间加载到 JVM 中一次,并保留在内存中直到 webapp 被取消部署。此外,一旦方法完成执行并且所有本地引用都被垃圾收集,该方法的内存将被回收。

于 2013-04-18T13:45:24.147 回答