-2

Which one is more performant?

  1. Stream.of(stringArray).collect(Collectors.toList())
  2. Arrays.asList(stringArray)
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • 6
    They do different things. One results in a new list, copied from the array; the other results in a list backed by the array. – Andy Turner Jul 06 '20 at 08:34
  • 2
    I would expect the second version to be more efficient, but there is only one way to be sure: measure. – assylias Jul 06 '20 at 08:40

1 Answers1

1

You can do a test by creating a very large array and calculate the elapsed time of the two technics that you mentioned, and then just compare the two elapsed time. here is an example:

String[] veryLargeStringArray = {"","",...};

long starttimelist1 = System.nanoTime();
List<String> list1 = Stream.of(veryLargeStringArray).collect(Collectors.toList());
long endtimelist1 = System.nanoTime();
System.out.println("list1 time : "+(endtimelist1-starttimelist1));
    
long starttimelist2 = System.nanoTime();
List<String> list2 = Arrays.asList(veryLargeStringArray);
long endtimelist2 = System.nanoTime();
System.out.println("list2 time : "+(endtimelist2-starttimelist2));

And in my opinion, the Stream.of(veryLargeStringArray).collect(Collectors.toList()) is slower one because it has lot od sub-calls than Arrays.asList(veryLargeStringArray) which does just an instantiation of an ArrayList. And Finaly it depends on what you want to do in your code.

A.RAZIK
  • 434
  • 3
  • 8
  • 1
    This is not how you measure performance. https://stackoverflow.com/q/504103/829571 – assylias Jul 06 '20 at 09:32
  • right, but I think with `nanoTime` is largely sufficient instead of `currentTimeMillis` – A.RAZIK Jul 06 '20 at 10:04
  • nanotime is not the problem here, the testing is. – Axel Jul 06 '20 at 10:11
  • 1
    The only correct statement is the last sentence: *it depends on what you want to do in your code*. Do you need a mutable list that changes the original array when modified or do you need a list of unspecified mutability that represents a copy of the original array… – Holger Jul 06 '20 at 10:47