Should I iterate over the Java assembly to get a subset or convert it to an array first and then iterate over it?

I call an API that returns a set of objects to me. I want to get a subset of objects. I think of two solutions. Which one will give me the best performance? Based on my understanding, calling toArray() will basically go through the collection once. If true, would a solution be better?

Solution 1 -

 public static List<String> get(UUID recordid, int start, int count) { List<String> names = new ArrayList<String>(); ... Collection<String> columnnames = result.getColumnNames(); int index = 0; for (UUID columnname : columnnames) { if ((index >= start) && (index - start < count)) { names.add(columnname); } index++; } return names; } 

Solution 2 -

 public static List<String> get(UUID recordid, int start, int count) { List<String> names = new ArrayList<String>(); ... Collection<String> columnnames = result.getColumnNames(); String[] nameArray = columnnames.toArray(new String(columnnames.size())); for (int index = 0; index < nameArray.length && count > 0; index++, count--) { names.add(nameArray[index]); } return names; } 
+6
source share
4 answers

Definitely, iterating through a collection is better than converting it to an array first and then iterating through an array.

The second approach involves additional time and memory:

  • Distributed memory for array
  • Filling the array with the contents of the collection
+7
source

If your collection is a list, you can use the subList(fromIndex, toIndex) .

Example:

 List<String> x = new ArrayList<String>(); List<String> y = x.subList(5, 10); 
+18
source

I think subList answer is the way to go.

 public static List<String> get(UUID recordid, int start, int count) { Collection<String> columnnames = result.getColumnNames(); List<String> names = new ArrayList<String>(columnnames); return names.subList(start, start+count); } 
+2
source

If you have a list, use the subList method. Here is an example of this:

 private static void doTestListBreak() { for (int i=0; i<= 300; i++) { for (int delta=1; delta<= 30; delta++) { testListBreak(i, delta); } } } public static void testListBreak(int numItems, int delta) { if (delta <= 0) return; log("list(" + numItems + "): "); List<Integer> list = new ArrayList<Integer>(); for (int i=0; i < numItems; i++) { list.add(i); } for (int i=0; i < list.size(); i=i+delta) { int max = Math.min(list.size(), i + delta); List<Integer> subList = list.subList(i, max); log("list(" + numItems + "," + delta + "): " + subList); } } public static void log(String msg) { System.out.println(msg); } 
0
source

Source: https://habr.com/ru/post/912514/


All Articles