Recycler Object for Object Pool Pattern

Creating or destroying an object is never free and JavaScript is no exception. Generally, the cost of creating/destroying an object in JIT-optimized JavaScript runtimes doesn't affect performance, but other languages will have a performance hit as well. The real culprit is the increase in your application's memory footprint (watch the memory tab in a developer tool while running the tests below for an illustration). This is why, in most cases, reusing a single object is much more efficient than creating new objects.

The Recycler Object Pattern (Recycler Pattern) is the first part of this two part post on the recycler pattern and object pools. A recycler object is instantiated once and reused. It should have an initialization function to set internal variables and a recycler function to return the object to its base state, and be consumed completely between initialization and recycling. For simplicity, we’ll use JavaScript to showcase a Point recycler object, but these principles apply to other languages as well.

How do it…

Here is a simple data holder object:

function Point(x, y) {
    this.x = x;
    this.y = y;

Here is the same data holder object with an initialization and recycler function:

function Point() {
    this.recycle = function() {
        this.x = null;
        this.y = null;
    this.init = function(x, y) {
        this.x = x;
        this.y = y;

Create a bunch of Point objects in a tight loop:

for (var i = 1000000; i >= 0; i--) {
    var point = new Point(i, i);
    // do something with point

Versus doing the same with the recycler object:

var recyclerPoint = new Point();
for (var i = 1000000; i >= 0; i--) {
    recyclerPoint.init(i, i);
    // do something with recyclerPoint

See the runtime performance of the Many object test versus the Recycler object test on your device (average of 5 runs on 1M iterations printed to console). On Chrome the JIT does some optimizations to speed up the non-recycler case, so it's not always faster (I was seeing the recycler case consistently faster in Safari and FireFox), but look at the memory timeline if interested in the memory savings (there should be a spike from the non-recycler case and a mostly flat line from the recycler case).

How it works…

While this is a bit of a contrived example, especially since JavaScript engines have so many optimizations for minimizing the cost of object creation/destruction, it does a good job demonstrating what a recycler object looks like. Also, in some browsers (especially older IEs) there will be big performance gains. More importantly memory usage will be more consistent, instead of spikes. This is very useful when not wanting to trigger a GC pause during animations.

For JavaScript, I find this pattern particularly useful, when working with the mousemove event, animation loops, and JSON objects. For a more heavy-weight language like Java, this pattern is useful almost anytime an object needs to be quickly instantiated more than a couple dozen times. And mobile frameworks make heavy use of recycled objects, since memory is often a constraint.

The big gotcha with this pattern is that you cannot store any references to, especially any closures of, the recycler object, as it will most likely be recycled and reused, causing the wrong values to be stored in the outside reference.

Start Using SRCSET IMG Attribute For Serving Device Specific Images

The article, JavaScript Low Resolution Image Replacer, discussed a JavaScript solution for replacing low resolution images with higher resolution ones after the page finishes loading all the initial resources (thereby reducing the load time of your pages). But what about loading different image sizes based on the resolution of the user’s device. We could write a JavaScript solution for this (and some developers have), but HTML 5 already introduces the concept of <img srcset[

JavaScript Low Resolution Image Replacer

This is a handy, yet very simple, widget I was hacking on to replace loading or low resolution images with higher resolution ones once the document has finished loading.

How do it…

The widget is built using the jQuery plugin system and here is the complete code:
 (function($) { var isLoaded = false, REPLACEMENT_CLASS = "replacement-class", REPLACEMENT_RCLASS = "replacement-rclass", REPLACEMENT_URL = "replacement-img", TIMER = 500; $(window).load(function() { isLoaded = true; }); function ...

Network Information API Polyfill

One of the many new HTML5 APIs slowly being implemented by browsers is the Network Information API[2]. It exposes information about the type of network that the connecting device is using. In theory, this allows developers to optimize content around the connection speed of the user. However, as with most HTML5 APIs it is supported only by some browsers with/without prefixes, and has a legacy implementation, so a polyfill is useful when working with ...

Detecting Object Mutations by Counting Properties

Have you ever included a library and wonder, "how much did this library add to the window object", or passed an object into a function and asked yourself, "did that function modify my object"? Instead of reading the source code, this article shows a quick trick for answering these questions.

How do it…

For starters we need a function to count the number of properties on an object:
 function fnCountProperties(o) { var ...

Using Google Play Games on the Web

As many of you know, I now work for Google on the Play Games Team. We provide APIs for game developers, implementing useful features like leaderboards and achievements, so the developer doesn't have to. While many Android developers are using our services, adoption on the web could be better, so lets take a look at how to integrate the Google Play Games Services achievements into a web game.

Getting ready

Become a Google developer ...

Site Outage Fixed - Down for 32 hours :(

I apologize that the site has been down for a couple of days. It was a perfect storm of events. For starters, Amazon told me about two weeks ago that my server was going to be terminated and that I should do something about it (they do this now and again, as they upgrade equipment). And like any good developer, I was procrastinating until the last minute (Wednesday this week). Then on Tuesday, I received ...

Event Bubble & Capture Phases

One of the less understood, but powerful feature of browser events are their phases. According to the W3C level 2 spec there are three phases[1]: AT_TARGET=2, BUBBLING_PHASE=3, and CAPTURING_PHASE=1. Most browsers also implement a fourth phase[2]: NONE=0.

Getting ready

Just a quick note that everything discussed in this article is for modern browsers (all browsers except IE <9). Prior to IE 9, Internet Explorer used its own event system, instead of conforming ...

Passing Objects into addEventListener Instead of Functions

I was reviewing the browser event stack the other day and was reminded of a rarely used feature of addEventListener that allows developers to autobind the execution context object, instead of requiring a call to bind or using a library, that is worth sharing, if you weren’t already aware.

How do it…

Typically, when attaching an event, we write:
 var myObj = { handleEvent: function (evt) { // 'this' will be scoped ...

Running Android Tests on a Device or Emulator

I have not been doing much web development lately, so its been difficult to come with interesting topics. However, I have been doing a lot of android development and since many engineers have to work cross discipline, I think an android article be relevant. This article will discuss how to run unit tests against your android code, directly on the android device or emulator.

Getting ready

You will need to install the