今天在调优的过程中发现某一个接口有些慢,sql查询不到一秒,整体接口返回数据达到3、4秒。
先上代码:
List<String> feedAccount = feedHomePageService.selectFeedAccount();
accountNewList.removeIf(o -> !feedAccount.contains(o.getAdvertiserId()));
accountNewList大概12W条数据,整个过滤下来大概花费3~4秒
改成set之后:
List<String> feedAccount = feedHomePageService.selectFeedAccount();
long time = System.currentTimeMillis();
// set去重要比list效率高
Set<String> feedAccountSet = new HashSet<>(feedAccount);
accountNewList.removeIf(o -> !feedAccountSet.contains(o.getAdvertiserId()));
LogUtil.info(logger, "feedAccountSet remove account by feedAccount", System.currentTimeMillis() - time);
从输出日志可以看出效率瞬间提升,只用了12ms
[INFO] [2021-11-23 11:08:44][com.xx.xx.xx.xx.homepage.HomePageService]4b1dc5a6-5519-4432-86fd-f19263aa9412 xxx@xxx feedAccountSet remove account by feedAccount 12
分析:
set的HashSet.contains()方法,底层是通过HashMap来实现的。而HashMap的查找速度是很快的
List和Set contains原理实现大家可以看一这篇文章:
List和Set contains原理