Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Introduction of JDK8 Stream performance

Shulou Source: shulou.com Published: 2022-06-02 10:17:36 09月15日 Update

This article mainly explains the "introduction of JDK8 Stream performance", the content of the explanation is simple and clear, easy to learn and understand, now please follow the editor's ideas slowly in depth, together to study and learn "JDK8 Stream performance introduction" bar!

I. scene

When writing the code, you want to replace the previous for loop with jdk8's stream, as follows:

/ / for method Set keys = Sets.newHashSetWithExpectedSize (list.size ()); for (T data: list) {keys.add (getWrapRedisKey (data));} / / stream method Set keys = list.stream (). Map (this::getWrapRedisKey) .questions (Collectors.toSet ())

Stream can be solved with a very elegant one line of code, while for requires three lines of code, which makes it much more productive.

However, the for loop can achieve the initialization capacity, which can greatly improve the performance when the rehash is triggered frequently by add and the linked list changes to a red-black tree, so does the Collectors.toSet method of stream's api set the initialization capacity?

View the source code:

III. Testing

Talking is cheap,show me the code

Simply wrote a test code

Public static void main (String [] args) {int expectSize = 1000000; List source = generateData (expectSize); long start = System.currentTimeMillis (); testFor (source); / / testStream (source); System.out.println (System.currentTimeMillis ()-start);} private static void testFor (List source) {Set sets = Sets.newHashSetWithExpectedSize (source.size ()); for (String s: source) {sets.add (s) }} private static void testStream (List source) {source.stream () .collect (Collectors.toSet ());} private static List generateData (int size) {List list = Lists.newArrayListWithCapacity (size); for (int I = 1; I

Tags: Performance code capacity methods learning content scenarios data results problems loops tests frequency elegance one line and at the same time ideas situations articles Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker Linux Shulou Technology macOS Apple