Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Property compute is expensive
import Ember from 'ember';
var fib = function(n){
switch(n){
case 0: return 0;
case 1: return 1;
default: return fib(n-1) + fib(n-2);
}
};
var ItemModel = Ember.Object.extend({
someProperty: Ember.computed('index', 'root.clock', 'root.computationCost', function(){
return fib(Math.floor(this.get('root.computationCost'))) + this.get('root.clock') + this.get('index');
}),
});
export default Ember.Controller.extend({
appname: 'Ember Twiddle',
requestedItemCount: 1,
refreshRate: 10,
enableIncreasingItems: false,
computationCost: 0,
refreshDelay: Ember.computed('refreshRate', function(){
var refreshRate = this.get('refreshRate');
var refreshDelay = 1000 / refreshRate;
return refreshDelay;
}),
init() {
this._super(...arguments);
this.set('startTime', (new Date).getTime());
this.updateClock();
},
willDestroy() {
this._super(...arguments);
Ember.run.cancel(this.clockTimeout);
},
clockMs: Ember.computed('startTime', function(){
var startTime = this.get('startTime');
var currentTime = (new Date).getTime();
return currentTime - startTime;
}),
clock: Ember.computed('clockMs', function(){
return Math.floor(this.get('clockMs') / 1000);
}),
updateClock: function() {
this.clockTimeout = Ember.run.later(this, function(){
this.notifyPropertyChange('clockMs');
this.updateClock();
}, this.get('refreshDelay'));
},
itemCount: Ember.computed('clock', 'requestedItemCount', 'enableIncreasingItems', function(){
if (this.get('enableIncreasingItems')){
return Math.floor(this.get('clock') / 20) * 1;
}
return this.get('requestedItemCount');
}),
items: Ember.computed('itemCount', function(){
var result = [];
for (var i = 0; i < this.get('itemCount'); i++){
result.push(ItemModel.create({root: this, index: i}));
}
return result;
}),
});
<h1>Welcome to {{appName}}</h1>
<br>
<br>
Clock: {{clock}}
<br>
RefreshRate: {{refreshRate}} times / sec <br />
RefreshDelay: {{input type='range' min=0 max=100 step=1 value=refreshRate}} {{refreshDelay}} ms <br />
requestedItemCount: {{input type='range' min=0 max=100 step=1 value=requestedItemCount}} {{requestedItemCount}} <br />
computationCost: {{input type='range' min=0 max=100 step=1 value=computationCost}} {{computationCost}} <br />
Enable Increasing Items: {{input type='checkbox' checked=enableIncreasingItems}}<br />
<br>
{{#each items as |item|}}
<span>{{item.index}} - {{item.someProperty}}</span>
{{/each}}
<br>
{
"version": "0.10.6",
"EmberENV": {
"FEATURES": {}
},
"options": {
"use_pods": false,
"enable-testing": false
},
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js",
"ember": "https://s3.amazonaws.com/builds.emberjs.com/beta/ember.prod.js",
"ember-template-compiler": "https://s3.amazonaws.com/builds.emberjs.com/beta/ember-template-compiler.js"
},
"addons": {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment