问题描述
前2天面试的时候,遇到一个代码优化的题目没有什么头绪,发出来大家讨论讨论要求优化 第一个fctPasOptimalmodifList 修改list里的值, traiteResultat 数据存储用于之后处理部分代码如下。。。 public final List<Integer> fctPasOptimal() { List<Integer> locNbList = new LinkedList<Integer> (); for (int i = 0; i < 30000; ++i) { Calendar locCalendar = new GregorianCalendar (); locNbList.add(computeNewValue(locCalendar.get (Calendar.YEAR), i)); } modifListe(locNbList) ; Double locResultat = 0.0 ; for (int i = 0; i < locNbList.size(); ++i) { final Double locTmpValue = doOperation(locNbList.get(i)); if (locTmpValue != null) { locResultat += locTmpValue ; } } traiteResultat (locResultat) ; return locNbList ; }
解决方案
public final List<Integer> fctPasOptimal() { List<Integer> locNbList = new LinkedList<Integer>(); // 在for循环外在定义,可节省内存 Calendar locCalendar = null; for (int i = 0; i < 30000; ++i) { locCalendar = new GregorianCalendar(); locNbList.add(computeNewValue(locCalendar.get(Calendar.YEAR), i)); } // 便于回收 locCalendar = null; modifListe(locNbList); Double locResultat = 0.0; Double locTmpValue = null; // 如果集合过大,建议只求一次size() int count = locNbList.size(); for (int i = 0; i < count; ++i) { locTmpValue = doOperation(locNbList.get(i)); // for循环里应该减少if判断,降低圏复杂度 locResultat += (locTmpValue != null ? locTmpValue : 0.0); } traiteResultat(locResultat); return locNbList; }