Using Big-Oh notation, we can generalise the time complexity of methods within the ArrayList
class.
For an ArrayList<>
the following operations can be defined as follows:
get()
has a time complexity of O(1)
add()
, clear()
and remove()
all have a time complexity of O(n)
removeAll()
has a time complexity of O(n^2)
From this, it can be seen that get()
has the least time complexity and doesn't depend on the size of the list to how it performs. You should also note add()
, clear()
and remove()
all run in linear time - which isn't as efficient but is not generally considered bad for performance.
According to the official documentation:
The size, isEmpty, get, set, iterator, and listIterator operations run
in constant time. The add operation runs in amortized constant time,
that is, adding n elements requires O(n) time. All of the other
operations run in linear time (roughly speaking). The constant factor
is low compared to that for the LinkedList implementation.
Why Big-Oh? (source)
Big O notation is a way of describing how quickly an algorithm will
run given an arbitrary number of input parameters, which we'll call
n
. It is useful in computer science because different machines
operate at different speeds, and simply saying that an algorithm takes
5 seconds doesn't tell you much because while you may be running a
system with a 4.5 Ghz multi-core processor, I may be running a 15 year
old, 800 Mhz system, which could take longer regardless of the
algorithm.
So instead of specifying how fast an algorithm runs in terms of
time, we say how fast it runs in terms of number of input parameters, or n
.
By describing algorithms in this way, we are able to compare the
speeds of algorithms without having to take into account the speed of
the computer itself.
Sources: Big-Oh cheatsheet and this answer