深度剖析树结构递归优化策略
祖传代码中使用递归生成树结构数据,效率低下,本文将针对以下java代码片段进行优化,提升树结构生成效率。
public list
这段代码中getchildlist方法存在效率问题。首先,childrenlist参数作为输出参数,仅在id == 0l时使用,这导致了不必要的参数传递。我们可以直接利用该方法的返回值,移除该参数。
其次,在getchildlist方法的循环中,反复调用childlist.get(i)降低了效率。我们可以引入一个中间变量缓存循环中的元素,或者使用增强型for循环来优化。
最后,在for循环内的if分支中,大部分代码是相同的,只有isleaf和children字段有所不同,我们可以将重复的代码提取出来,只处理差异部分。
立即学习“Java免费学习笔记(深入)”;
经过优化后的代码如下:
public List createGroupTreeNode() { List childrenList = getChildList(0L); // ....}public List getChildList(Long id) { List childList = baseMapper.childListByParentId(id); if(childList != null && childList.size() > 0){ List tempMap = new ArrayList(); 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 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;}
通过这些修改,我们简化了代码,并提高了代码的可读性和效率。
以上就是Java树结构递归生成效率低下如何优化?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/169311.html