I am calling an API which returns me a collection of objects. I want to get a subset of the objects. There are two solutions that I am thinking. Which one would give me better performance? Based on my understanding, the toArray()
call mainly will iterate through the collection once. If that's true, then the solution one would 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;
}
Collection
not necessarily a List
ulmangt 2012-04-05 16:35
Definitely, iterating through a collection is better than converting it an array first, and then iterating through the array.
The second approach provides with extra time and memory expenses:
If your Collection is a List, you can use the subList(fromIndex, toIndex)
method.
Example:
List<String> x = new ArrayList<String>();
List<String> y = x.subList(5, 10);
I think the 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);
}
If you have a list, use the subList method. Here's an example of doing so:
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);
}
subList
- assylias 2012-04-05 16:22