it's true that adding single objects is slower. when i remember correctly that's because Vector is internally not growing by adding 1, but by a factor. to speed up appendClass you'd want it to grow by factor 2 or something smarter. but in the end you'll be close to the Vector class ...
but:
appending / concatenating whole arrays is indeed faster, see test:
Code:
import java.lang.reflect.Array;
int timer = 0;
void setup()
{
// max number of elements
//
int MAX = 10000;
// set up the arrays
//
T a[] = new T[0];
T b[] = new T[0];
for(int i = 0; i < MAX; i++){
a = (T[])appendClass(a, new T());
}
for(int i = 0; i < MAX; i++){
b = (T[])appendClass(b, new T());
}
// set up a vector
//
Vector c = new Vector();
for (int i = 0; i < MAX; i++) {
c.add(new T());
}
// test and time appendClassArray()
//
timer = millis();
a = (T[])appendClassArray(a, b);
println( millis() - timer );
println( a.length );
// test and time Vector.addAll( Collection c )
//
timer = millis();
c.addAll(Arrays.asList(b));
println( millis() - timer );
println( c.size() );
noLoop();
}
// Appending an object of a certain class to an array of the same class
// remember to cast (ClassName[]) in front of the function
Object appendClass(Object array, Object o)
{
Object newArray = Array.newInstance(array.getClass().getComponentType(), Array.getLength(array)+1);
System.arraycopy(array, 0, newArray, 0, Array.getLength(array));
Array.set(newArray,Array.getLength(newArray)-1,o);
return newArray;
}
// Appending an array of a certain class to another array of the same class
// remember to cast (ClassName[]) in front of the function
Object appendClassArray(Object array, Object oarray)
{
Object newArray = Array.newInstance(array.getClass().getComponentType(), Array.getLength(array)+Array.getLength(oarray));
System.arraycopy(array, 0, newArray, 0, Array.getLength(array));
System.arraycopy(oarray, 0, newArray, Array.getLength(array), Array.getLength(oarray));
return newArray;
}
// A temporary class, just for testing.
class T
{
float x, y;
String txt;
T()
{
txt = "";
for(int i = 0; i < 5; i++)
txt = txt+char((int)random(60,120));
}
}
and .. arraycopy() is now (as of rev. 115) part of the processing-api:
fry wrote on May 11th, 2006, 1:28am:+ added arraycopy(from[], to[], count)
best,
F