关于java8 lambda表达式的性能问题

natural_ 2017-08-04 05:44:42
写了一个比较懒的测试代码:
	ArrayList<TestPo> list2 = new ArrayList<TestPo>();
for (int i = 0; i < 100; i++) {
list2.add(new TestPo());
}
long l3 = new Date().getTime();
list2.forEach(t ->t.setId(2));
long l4 = new Date().getTime();
System.out.println("lambda:" + (l4 - l3));

long l1 = new Date().getTime();
for (TestPo t : list2)
t.setId(1);
long l2 = new Date().getTime();
System.out.println("foreach:" + (l2 - l1));

然后运行的结果:
lambda:43
foreach:0
????????????????
为什么会慢这么多呢 看有的人写的博客这个性能不应该是一样的只是写法区别而已吗??
求解
...全文
586 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
引用 3 楼 司青 的回复:
You are obviously encountering the first-time initialization overhead of lambda expressions. As already mentioned in the comments, the classes for lambda expressions are generated at runtime rather than being loaded from your class path. However, being generated isn’t the cause for the slowdown. After all, generating a class having a simple structure can be even faster than loading the same bytes from an external source. And the inner class has to be loaded too. But when the application hasn’t used lambda expressions before, even the framework for generating the lambda classes has to be loaded (Oracle’s current implementation uses ASM under the hood). This is the actual cause of the slowdown, loading and initialization of a dozen internally used classes, not the lambda expression itself.
求出处
  • 打赏
  • 举报
回复
You are obviously encountering the first-time initialization overhead of lambda expressions. As already mentioned in the comments, the classes for lambda expressions are generated at runtime rather than being loaded from your class path.

However, being generated isn’t the cause for the slowdown. After all, generating a class having a simple structure can be even faster than loading the same bytes from an external source. And the inner class has to be loaded too. But when the application hasn’t used lambda expressions before, even the framework for generating the lambda classes has to be loaded (Oracle’s current implementation uses ASM under the hood). This is the actual cause of the slowdown, loading and initialization of a dozen internally used classes, not the lambda expression itself.
natural_ 2017-08-08
  • 打赏
  • 举报
回复
不不不 也弄了一个百万条的 差距也不小
解开者 2017-08-05
  • 打赏
  • 举报
回复
样本数据太少了,cpu稍微抖一下误差就不止这些了

50,526

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧