Reputation: 1659
I know this might be simple, I have a situation where I need to decide between using four for-loops to (two to count and remove null elements, two to add elements) merge two String arrays or use two for-loops with an ArrayList and convert the ArrayList to array using ArrayList.toArray().
Performance wise are there any differences between these two approaches?
EDIT
I had to drop the ArrayList with generics approach because of compatibility issues. But here is the earlier code.
List<String> newList = new ArrayList<String>();
for (String element : array1)
{
if (element != null)
{
newList.add(element);
}
}
for (String element : array2)
{
if (element != null)
{
newList.add(element);
}
}
return newList.toArray(new String[]{});
I wrote a new code with one loop, but I think I might be mentally killing the next one reading this code.
String[] newArr = new String[array1.length + array2.length];
int n = 0;
for (int i = 0; i < newArr.length; i++)
{
if (i < array1.length && array1[i] != null)
{
newArr[n] = array1[i];
n++;
}
if (i >= array1.length)
{
int a = 0;
if (array1.length < array2.length)
{
a = (i - array1.length) + (array2.length - array1.length);
}
else
{
a = i - array1.length;
}
if (array2[a] != null)
{
newArr[n] = array2[a];
n++;
}
}
}
return newArr;
And finally got to know that null element check won't be needed so went ahead with this simple code.
String[] newArr = new String[array1.length + array2.length];
System.arraycopy(array1, 0, newArr, 0, array1.length);
System.arraycopy(array2, 0, newArr, array1.length, array2.length);
return newArr;
I guess from the discussion below the second method is the better performing one.
Upvotes: 0
Views: 142
Reputation: 5637
Assuming 1 for loop has O(n) time complexity, 4 for loops and 2 for loops would have the same time complexity
4*O(n) = O(n)
2*O(n) = O(n)
But using arrays instead of ArrayLists would take less memory. So go with the first alternative.
Upvotes: 3
Reputation: 8347
as with second option 2 iterations over collection will be saved, this will definitely improve performance if count of objects in list is high.
Upvotes: 0
Reputation: 1464
Try to avoid looping as much as you can because every time u loop with n
elements the time and space complexity increases by n
.
Please paste your code.
Upvotes: 0