Thursday 12 January 2012

getters and built-in classes

Following on from yesterday's post, an obvious question is whether getters and setters are used for built in classes. The answer is yes, but not for all of them, and it is important to know which.


I won't post code for this, as the code is straightforward but lengthy, and is easily inspected at wonderfl where I've created this program to demonstrate it. It defines two classes, one derived from Vector3D, one derived from Bitmap. The purpose of each is to compare accessing the built-in members of the classes with members added by the derived classes.


In short, the results show that built-in members of Vector3D are as fast as member variables defined in the derived class, while the built-in members of Bitmap are over four times slower. The obvious conclusion is they use getters (and setters), and they do.


These members (x and y) are inherited from DisplayObject, a base class in ActionScript which all drawable objects in Flash are derived from. And in the documentation for this class, under 'Implementation', it states that getters and setters are used for these members.


So if you need to store the position of a game object store it separately, in another class or in fields added to the class alongside the built-in ones. Not only will it be many times faster but more accurate (as Twips are used internally). Only access the built in members when necessary, to e.g. update them as the object is moved.


Which members use getters and setters depends on the class. The Rectangle class, for example, uses getters and setters for some Number members but not others, as described in its documentation. The best thing seems to be to assume accessing built-in members of a class is slow unless you know otherwise, based on the documentation for that class.

No comments:

Post a Comment