I want to know the performance of .size()
method. Does this method returns a reference from the number of objects in the list (like a class member which is incremented every time when an object is added to the list)? Or does it iterate through all objects?
Which one is more efficient?
Calling .size()
every time:
List<Vector3> objects = getCoords();
for (int x = 0; x < objects.size(); x++){
for (int y = 0; y < objects.size(); y++){
for (int z = 0; z < objects.size(); z++){
drawShape(x, y, z);
}
}
}
Or by saving to a local variable:
List<Vector3> objects = getCoords();
int size = objects.size();
for (int x = 0; x < size; x++){
for (int y = 0; y < size; y++){
for (int z = 0; z < size; z++){
drawShape(x, y, z);
}
}
}
Let's assume that we have > 30.000 objects in the list.
Which one is more faster/efficient?
Does it matter if we use an ArrayList<T>
or a List<T>
?
What about simple statements: .size()
or .isEmpty()
if (objects != null && objects.size() > 0){
doThis();
}
or by calling .isEmpty()
if (objects != null && !objects.isEmpty()){
doSomethingElse();
}
The java. util package provides the List interface for maintaining the ordered collection. A List can contain the null and duplicate values.
The List interface allows storing the ordered collection. It is a child interface of Collection. It is an ordered collection of objects in which duplicate values are allowed to store. List preserves the insertion order, it allows positional access and insertion of elements.
One more way to detect duplication in the java array is adding every element of the array into HashSet which is a Set implementation. Since the add(Object obj) method of Set returns false if Set already contains an element to be added, it can be used to find out if the array contains duplicates in Java or not.
In order to optimize the performance of ArrayLists, it is advisable to set a large enough initial capacity when initializing an ArrayList to incorporate all your data. This will allocate a large enough chunk of memory so that you will probably not need to perform the allocation process again.
Java List
uses a instance variable to handle the size. It is incremented when you add, and decremented when you decrease. Calling list.size()
returns a variable, and is therefore O(1).
List.size()
would (theoretically) look something like:
public int size() {
return this.size;
}
Calling List.isEmpty()
is a boolean check on whether the instance variable size
is equal to 0 or not.
public boolean isEmpty() {
return (this.size==0);
}
Since this is a instance variable, it doesn't matter (from what I know) what type of List
you use, since all inherit a general interface and have the required add()
and other functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With