Haxe – Organize instances

To tend sheep

Often in projects, you will care for a bunch of object/instances of the same type. It doesn’t matter if it’s video player, data models or something else. You are a conductor and have to conduct your orchestra.

How you will organize them? How you will loop over this instances to get or set a property or call a method?

Way1 – Free like a bird

var instance1:AnyClass = new AnyClass();
var instance2:AnyClass = new AnyClass();
var instance3:AnyClass = new AnyClass();

How you will iterate over that instances? Not at all, because they are not grouped. This is the most unwieldy solution, because you have to call each instance separately.

instance1.dosomething();
instance2.dosomething();
instance3.dosomething();

Way2 – Grouped in a map

var map:Map<String, AnyClass> = new Map();
map.set(„instance1“, new AnyClass());

And how about iterate over the map?

for( key in map.keys()){
	key.dosomething();
}

This solution will do the job, but it’s but much slower than the next solution.

Way3 – Grouped in an Array

var group:Array<AnyClass> = [];
group.push(new AnyClass());

How to iterate over an array?

for(i in 0...group.length){
	group[i].dosomething();
}

This solution is approximately 7 times faster than the solution with the map.
Now you might say, „I don’t care, because I have only 10 instances“.
You are right, but in my opinion if you can speed up the performance, you should do it!
Reducing a view milliseconds here and there will make the difference in the end.

Why is this way faster?

Because the job of the for loop with the array only has to handle a counter and the length of the array.
Compared with the map an Array is more flat having just singular values. You can easily access the values by it’s index.

The loop with the map is a bit more complex. The map holds key value pairs. If you would like to iterate over a map, you have to call the map.keys() method. This method will build and provide a structure that makes it possible to loop over the values. That’s why looping over an object takes much longer.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>