Is calling destroy() on an Object necessary?

I’m wondering if calling destroy() on an Ember.Object that was explicitly created (i.e. not automatically created by the Ember framework) is necessary.

The documentation says that destroy() cleans any meta and bindings on the object. If you set null out the property that stored the Object, would that be sufficient or will data still be leaked and the object not be garbage collected?

Ember.Component.extend({
    testObject: null,  
    
    init() {
        this._super(...arguments);
        this.set('testObject', Ember.Object.create());
    },

    willDestroy() {
        this._super(...arguments);
        this.set('testObject', null); // Will this allow testObject to be garbage collected?
    }
});

That depends on what’s in the object and what kind of property you use, but as a rule, you should destroy objects you create. If you use event handlers or computed properties (which is usually the case), they store references to the object into dependent keys’ objects.

Plus changing…

this.set('testObject', null);

to…

this.get('testObject').destroy();

… is not that difficult.

Swaping null to destroy() doesn’t work for all cases, as there are times were I want to replace the object and I want to know if destroy() is needed for that case as well. The official recommendations and a technical understanding of why is what I’m hoping to gain.

As I wrote, observers and computed keys create references to the object they live on. They will not get removed unless you call destroy. That’s the technical explanation, which you can easily verify by yourself if you are so inclined (simply write something with console.log in a computed property and update the dependent key after you’ve set the reference to null, it will still write to the console).

As for official recommendations, not being part of Ember team, I cannot help with that.

1 Like