This post originated from an RSS feed registered with Agile Buzz
by James Robertson.
Original Post: Bindings
Feed Title: Michael Lucas-Smith
Feed URL: http://www.michaellucassmith.com/site.atom
Feed Description: Smalltalk and my misinterpretations of life
You may have become acquainted with VisualWorks's namespaces where you can place classes in a foreign namespace and reference them from your namespace by prefixing them. For example: SDL.SDLObject grabs an SDLObject class from the SDL namespace.
But it comes at a cost. It's dynamic, in that it does it at runtime and it can create garbage. Normally, this is not an issue, but if you're writing speed critical code, you want neither of these things to occur.
How can you solve this?
Well, it happened on me that I needed a local reference to my foreign class on my extension of a base class in my package. Let me elaborate. I had an extension to ColorValue in SDL Core which has an extension method that turns a ColorValue in to an SDL color. To do this, it needs to use SDL.SDLInterface. This method was being called a lot when drawing pixels and was both wasting time finding SDL.SDLInterface and creating garbage trying to do so.
So I needed a solution that would make it fast but also not affect the base ColorValue class. My first thought was that I needed to export my namespace of SDL in to the UI namespace. This appears not to be possible.
That's okay though, because there's another way! Instead, we can use a Shared Variable - these are package oriented, which means me adding a Shared Variable will exist in my package, not the base package. The initialiser of the Shared Variable is SDL.SDLInterface. I called the Shared Variable SDLInterface. Now in my code I can reference SDLInterface instead of SDL.SDLInterface and the binding is now local.
No dynamic binding takes place now, no garbage, no time looking up the class. It's non-intrusive to the rest of the system too. Another trick to pocket for later.