Which is faster and takes less amount of time (in nanoseconds) in JAVA between the two?
get() or elementAt()
I’m using them to return element stored in an object. And speed is critical, therefore I wanted to know which is more feasible and faster amongst the two.
public E peek() {
int len = size();
if (len == 0)
throw new EmptyStackException();
return get(len - 1);
}
or
public E peek() {
int len = size();
if (len == 0)
throw new EmptyStackException();
return elementAt(len - 1);
}
First off, you didn’t tell us what data structure you are working with. So, I’ll go with the assumption that you are using
Vectoror someVectorderivative.The two methods are identical according to the documentation:
http://download.oracle.com/javase/1,5.0/docs/api/java/util/Vector.html
That being said however,
elementAt(idx), dates back to the days when Vector did not follow the List patterns (by extendingAbstractList) — if you read the full docs you’ll see that Vector was modified to implement the List interfaces.Therefore, I would expect
get(idx)to provide the fastest speeds, andelementAt(idx)to simply call through toget(idx). At any rate, the difference in speed is going to be almost nothing — and you should look elsewhere if you’re looking to get a performance bump.