I have written up a data structure in Java that supports the following features:
get(i)
set(i, e)
add(e)
remove(e)
contains(e)
size
Elements must remain in order and iteration needs to be as fast as possible. The code does not require thread safety.
I am looking for ways to improve the speed further. It is critical to reduce times to as small as possible because this code will be invoked hundreds of thousands of times per second. I believe it's possible to optimize my stream()
method!
This is my current solution which seems to work:
import java.util.Iterator;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public final class Indexer<E> implements Iterable<E> {
private final int minIndex;
private final Object[] arr;
private int size = 0;
private int highest;
public Indexer(int minIndex, int capacity) {
this.minIndex = highest = minIndex;
arr = new Object[capacity];
}
public Indexer(int capacity) {
this(0, capacity);
}
@SuppressWarnings("unchecked")
public E get(int index) {
return (E) arr[index];
}
@SuppressWarnings("unchecked")
public E set(int index, E element) {
Object last = arr[index];
arr[index] = element;
if (last == null && element != null) {
size++;
if (highest < index)
highest = index;
} else if (last != null && element == null) {
size--;
if (highest == index)
highest--;
}
return (E) last;
}
public int add(E element) {
int index = nextIndex();
set(index, element);
return index;
}
public void remove(E element) {
for (int i = minIndex; i <= highest; i++) {
if (element == arr[i]) {
set(i, null);
return;
}
}
}
public boolean contains(E element) {
for (E e : this) {
if (element == e)
return true;
}
return false;
}
public int size() {
return size;
}
public int nextIndex() {
for (int i = minIndex; i < arr.length; i++) {
if (null == arr[i])
return i;
}
throw new IllegalStateException("Out of indices!");
}
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
private int pointer = minIndex;
@Override
public boolean hasNext() {
return size > 0 && pointer <= highest;
}
@Override
@SuppressWarnings("unchecked")
public E next() {
return (E) arr[pointer++];
}
};
}
public Stream<E> stream() {
return StreamSupport.stream(spliterator(), false);
}
}
+= -1
to-= 1
or just--
. Remember that the JIT does a lot of things very well, including squeeze every bit of speed out of the program once it's called enough. – QPaysTaxes Jun 29 at 18:231 2 3 4 5
, then remove3
, then add6
, currently your order becomes1 2 6 4 5
. Is that intended? Also, can you explain the purpose ofminIndex
? In what situation would you create anIndexer
with aminIndex
that is not 0? Lastly, which operations will be performed hundreds of thousands of times per second? Is itadd
,remove
,contains
,get
, or iterating? – JS1 Jun 29 at 18:40