虚拟线程性能对比:IntStream与普通for循环为何差异巨大?
虚拟线程创建的性能差异问题
我尝试创建100000个包含简单打印语句的虚拟线程,发现两种实现的执行时间差距极大:
错误的IntStream实现(预估耗时2毫秒)
List<Thread> threads = IntStream.of(0, 100000) .mapToObj(it -> Thread.ofVirtual().unstarted(() -> System.out.println(Thread.currentThread()))) .toList(); long begin = System.currentTimeMillis(); threads.forEach(Thread::start); for (Thread thread: threads) { thread.join(); } long end = System.currentTimeMillis(); System.out.println("time taken: " + (end - begin) + " milliseconds");
普通for循环实现(预估耗时6925毫秒)
List<Thread> threads = new ArrayList<>(); for (int i = 0; i < 100000; i++) { threads.add(Thread.ofVirtual().unstarted(() -> System.out.println(Thread.currentThread()))); } long begin = System.currentTimeMillis(); threads.forEach(Thread::start); for (Thread thread: threads) { thread.join(); } long end = System.currentTimeMillis(); System.out.println("time taken: " + (end - begin) + " milliseconds");
我知道IntStream比普通for循环更节省内存,但认为两者并无本质性能差异,因此疑惑为何会出现如此大的性能差距。测试环境为8核Mac设备。
更新说明
- 上述代码中
IntStream.of(0, 100000)仅传入两个数值,并非生成0到100000的范围序列,属于错误用法,这是导致耗时差异的核心原因。 - 移除打印语句,改用HashSet跟踪所用平台线程数量后,在8核系统中,使用for循环和
IntStream.range()创建100000个虚拟线程的预估执行时间均约为150毫秒。 - 正如之前的结果所示,添加打印语句会带来大量性能开销。
内容的提问来源于stack exchange,提问作者Rahul Raj
相关产品推荐
相关产品推荐

