本文对递归生成树结构的代码进行了性能优化分析。代码的主要问题是使用低效的递归方法和一些优化的细节。
原始代码中,creategrouptreenode 函数调用 getchildlist 函数递归生成树形结构。getchildlist 函数接收父节点 id 并且以列表为参数,对子节点进行递归查询并添加到列表中。但是,这种方法存在效率问题。
首先,getchildlist 函数的第二参数 childrenlist 只有当它实际上是一个输出参数时 id == 0l 只有在使用之前。 这导致了不必要的参数传输和内存费用。我们可以直接修改它 getchildlist 将函数返回生成的子节点列表,以消除冗余参数。 修改后的 creategrouptreenode 可直接使用函数 getchildlist 简化代码结构,提高功能返回值的效率。
其次,在 getchildlist 函数的 for 循环中,反复调用 childlist.get(i) 获取 basegroup 对象,造成不必要的性能损失。 通过引入中间变量缓存,我们可以 childlist.get(i) 结果,或直接使用增强型 for 避免重复访问数组元素。
此外,for 循环内部的 if 在分支条件判断句中,大多数代码都是相同的,只有 isleaf 和 children 属性值不同。 我们可以提取公共部分,只保留不同部分的判断,从而简化代码,提高可读性。
通过上述优化,可以有效提高代码效率,减少不必要的内存费用和计算次数。 具体优化方案如下:
修改后的 creategrouptreenode 函数:
public list<map> creategrouptreenode() { list<map> childrenlist = getchildlist(0l); // ... }
修改后的 getchildlist 函数:
public List<Map> getChildList(Long id) { List<BaseGroup> childList = baseMapper.childListByParentId(id); if(childList != null && childList.size() > 0){ List<Map> tempMap = new ArrayList<Map>(); for (BaseGroup it : childList) { Map map = new HashMap(); map.put("id", it.getId()); map.put("text", it.getNumber() + " - " + it.getName()); map.put("icon", "fa fa-folder"); Map subMap = new HashMap(); subMap.put("opened", false); map.put("state", subMap); List<Map> mylist = getChildList(it.getId()); if (mylist == null) { map.put("isleaf", "1"); } else { map.put("isleaf", "0"); map.put("children", mylist); } tempMap.add(map); } return tempMap; } return null; }
以上是如何优化递归生成树结构代码的性能?详情请关注图灵教育其他相关文章!
