I'm writing a performance-critical method in Java which uses a stack of double
values to store the (x, y) coordinates of points. At the moment, I'm using Stack<Double>
, but I realize that due to the cost of autoboxing, this might cause some performance issues. The coordinates usually change between calls, which is why caching the Double
wrappers wouldn't help.
Therefore, I'm looking for a hypothetical class, let's call it DoubleStack
, with behavior and interface similar to Stack<T>
, but operating on primitives only. Is there an oft-used class with such behavior, or better yet, a library consisting of primaries-storing alternatives to popular containers, including lists, stacks and queues?
I agree with the comment about premature optimization, but just for the fun of it, here's a trivial DoubleStack implementation:
public class HeresYourDoubleStack {
private int size = 0;
private double[] values= new double[16];
public int size() {
return size;
}
public double pop() {
if(size==0)throw new NoSuchElementException();
return values[size--];
}
public void push(double value) {
resizeIfNecessary();
values[size++]=value;
}
private void resizeIfNecessary() {
if(values.length==size){
double[] tmp = new double[size * 2];
System.arraycopy(values,0,tmp,0,size);
values=tmp;
}
}
}
Not tested, and definitely not thread safe.