Arrays.asList vs. Arrays.stream to use forEach()

前端 未结 3 797
生来不讨喜
生来不讨喜 2020-12-31 05:12

If you have an Array and you want to use the Java8 forEach() method, which approach is better or more efficient:

Arrays.asList(new String[]{\"hallo\",\"hi\"}         


        
3条回答
  •  时光取名叫无心
    2020-12-31 05:53

    Arrays.asList() method................: 22 ms
    Arrays.stream() method................: 26 ms
    Stream.of() method....................: 26 ms
    Arrays.asList() (premade array) method: 8 ms
    Arrays.stream() (premade array) method: 30 ms
    Stream.of() (premade array) method....: 17 ms
    

    When you change doSomething to actually do nothing as follows:

    public static void doSomething(String s){
    }
    

    Then you're measuring the actual speed of these operations instead of the operation String = String + String; This is what doSomething was doing, and of course it is about the same speed consistently. However, the actual speed isn't the same and asList with a premade array is much faster.

    The real result here has already been noted by others that you should beware of the stream as it is typically 4 times slower than the plain old java (non-lambda) approach.

提交回复
热议问题