Ember.computed.filter() vs Ember.Array.filter()


#1

Hi everybody!

For some controller, in its model, there is a property which is an array of Ember objects. In the controller I have to introduce another property which is computed from that array coming from model by filtering it on a particular object property value.

I’ve implemented the required logic using Ember.Array.filter() and a controller computed property. But there is also Ember.computed.filter() which seems also to be a solution in this case.

What is the difference between Ember.computed.filter() and Ember.Array.filter()? What are preferred usages of each?

Thank you!


#2

Ember.Array.filter() is just Ember’s own implementation for the ES5 Array.prototype.filter (MDN Docs). It takes an array, and returns a new array with the elements that passed your test.

Prior to the Glimmer engine, one of the major bottlenecks in rendering performance were long lists. One way to optimize was to make sure that you did not create an entirely new array when sorting/filtering/etc. Creating a new array would throw away all the DOM you had already created and start over.

Ember.computed.filter() is a way to perform “one at a time” operations on an array so that only the items that were added/removed are the ones that need to be rendered into the DOM. If you look at this under the hood, you’ll see that this is doing splice operations whereas Array.prototype.filter just pushes onto a new array.

With Glimmer (Ember 1.13+), this optimization is not really needed because it’s smarter about figuring out what’s changed by doing a deep comparison, rather than just assuming that if the array object changed, everything changed. I believe I’ve heard that the computed arrays are going to be deprecated in the 2.0 series. So, with that, it’s probably safe to stick with your solution using a computed property.

Hope this helps!