I am writing a simple 3D SW rendering engine. I have a default ArrayList<Object3D> containing the whole scene. Now, I want to be able to add, remove and select objects by name, like 3D editors do (because its MUCH more simple than mouse select, but still looking good in homework 🙂 ).
So, the first thing I thought is to have Hashtable for name and index to scene ArrayList. But, then I thought I could just simply save the scene using Hashtable directly, and go through it to render using iterator.
So I want to ask, in a 3D engine, what is speed-preferable? Because I will for-loop the scene many times per second, compared to selecting object. Is ArrayList any faster than iterated Hashtable? Thanks.
First, I suggest you use a
HashMapinstead of aHashtable, for the same reason thatArrayListis a better choice than aVector: less overhead due to useless synchronization.My guess is that iterating through an
ArrayListwill be faster than iterating through theSetreturned by aHashtable‘s (orHashMap‘s)entrySet()method. But the only way to know is to profile.Obviously, changes to the display list (other than appending or chopping off the last element) are going to be faster for a
HashMapthan for anArrayList.EDIT
So I followed my own advice and benchmarked. Here’s the code I used:
And here are the results for a typical run:
Clearly using an ArrayList is a big win (by a factor of 3-4) over a HashMap, at least for my style of iterating through a HashMap. I suspect the reason the array iterator is slower than array subscripting is all the iterator objects that need to be created and then garbage-collected.
For reference, this was done with Java 1.6.0_26 (64-bit JVM) on an Intel 1.6GHz quad-core Windows machine with plenty of free memory.