简体   繁体   中英

Efficient alternative to Stack<Double>

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.

There are several libraries that provide data structures for primitive types. One example is FastUtil , which provides a class DoubleStack which does exactly what you want. An alternative might be Trove4J , which provides a class TDoubleStack , and there are likely other libraries as well, but the two mentioned I've worked with.

Trove4J was kind of a standard for a long time, but seems not to get many updates any more, while FastUtil seems to be more actively developed. Also, in some of my (biased?) tests, FastUtil was faster in a number of cases, although I tested mostly for Maps, not Stacks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM