JDK8-lambda表达式四种forEach性能对比
jdk8新特性流Stream編程
看了網(wǎng)上一些性能的比較,這里自己寫一個(gè)進(jìn)行測試
對比以下四種?
普通forEach、java8中新的forEach、stream+forEach、parallelStream+forEach
package com.huajie.Lambda;
?
import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
import org.junit.Test;
?
import java.util.ArrayList;
import java.util.List;
?
@Slf4j
public class Mode2 {
?
? ? List<User> listUser = new ArrayList<>();
?
? ? @Before
? ? public void initList() {
? ? ? ? listUser = this.getListUsers();
? ? }
?
? ? @Test
? ? public void test() {
? ? ? ? //一般forEach
? ? ? ? long startSimpleTime = System.currentTimeMillis();
? ? ? ? for (User user : listUser) {
? ? ? ? ? ? user.toString();
? ? ? ? }
? ? ? ? long endSimpleTime = System.currentTimeMillis();
? ? ? ? System.out.println("Simple:" + (endSimpleTime - startSimpleTime));
?
? ? ? ? //java8中新的forEach
? ? ? ? long startLambda = System.currentTimeMillis();
? ? ? ? listUser.forEach(User::toString);
? ? ? ? long endLambda = System.currentTimeMillis();
? ? ? ? System.out.println("Lambda:" + (endLambda - startLambda));
?
? ? ? ? //java8中新的stream+forEach
? ? ? ? long startStream = System.currentTimeMillis();
? ? ? ? listUser.stream().forEach(User::toString);
? ? ? ? long endStream = System.currentTimeMillis();
? ? ? ? System.out.println("Stream:" + (endStream - startStream));
?
? ? ? ? //java8中新的parallelStream+forEach
? ? ? ? long startParallelStream = System.currentTimeMillis();
? ? ? ? listUser.parallelStream().forEach(User::toString);
? ? ? ? long endParallelStream = System.currentTimeMillis();
? ? ? ? System.out.println("ParallelStream:" + (endParallelStream - startParallelStream));
? ? }
?
?
? ? private List<User> getListUsers() {
? ? ? ? List<User> listUser = new ArrayList<User>();
? ? ? ? for (int i = 0; i < 10000000; i++) {
? ? ? ? ? ? listUser.add(new User("user" + i, i));
? ? ? ? }
? ? ? ? return listUser;
? ? }
?
?
}
package com.huajie.Lambda;
?
import lombok.Data;
?
@Data
public class User {
? ? private String name;
? ? private Integer age;
?
? ? public User(String name, Integer age) {
? ? ? ? this.name = name;
? ? ? ? this.age = age;
? ? }
}
1000W條數(shù)據(jù)
100W條數(shù)據(jù)
10W條數(shù)據(jù)
1W條數(shù)據(jù)
1000條數(shù)據(jù)
java8中新加入的forEach和普通的forEach臨界值大概在150W條
由以上測試能得到的結(jié)果:
150W條數(shù)據(jù)以下and10W以上:lambda>simple>stream>paralleStream
150W條數(shù)據(jù)以上:simple>lambda>stream>paralleStream
從性能上考慮:小數(shù)據(jù)量用普通的forEach就可以,沒有必要使用java8中的新出來的幾種,已經(jīng)在項(xiàng)目中使用的也不需要改回來,10W條也就幾毫秒的差距
————————————————
版權(quán)聲明:本文為CSDN博主「不懂的浪漫」的原創(chuàng)文章,遵循CC 4.0 BY-SA版權(quán)協(xié)議,轉(zhuǎn)載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/xiewenfeng520/article/details/88724349
總結(jié)
以上是生活随笔為你收集整理的JDK8-lambda表达式四种forEach性能对比的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Mysql 常用函数(19)- mod
- 下一篇: 亲兄妹恋知乎(亲兄妹恋小说)