Skip to content

Instantly share code, notes, and snippets.

@alexgb
Last active December 10, 2015 22:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alexgb/d056c39be639e83d373e to your computer and use it in GitHub Desktop.
Save alexgb/d056c39be639e83d373e to your computer and use it in GitHub Desktop.
Ember iteration performance helper
import Ember from 'ember';
const store = {};
const makeRelative = function(collection) {
return collection.reduce(function(acc, i) {
if (acc.last) {
acc.diffs.push(i - acc.last);
}
acc.last = i;
return acc;
}, { last: null, diffs: [] }).diffs;
};
const sum = _.partialRight(_.reduce, (acc, i) => acc + i);
const avg = (collection) => sum(collection) / collection.length;
const printMeasurements = function(label, timings) {
const relativeTimings = makeRelative(timings);
const avgTime = Math.round(avg(relativeTimings));
console.info(`Avg iteration time for ${label} : ${avgTime}ms (${timings.length} measurements)`);
};
export function measurePerformance(label, { wait = 500 } = {}) {
const measurements = store[label] = store[label] || {
timings: [],
runReport: _.debounce(function() {
printMeasurements(label, measurements.timings);
measurements.timings = [];
}, wait)
};
measurements.timings.push(performance.now());
measurements.runReport();
}
export default Ember.Handlebars.makeBoundHelper(measurePerformance);

Use the measure-performance helper inside a loop to measure the time for each iteration with an optional wait param that will be used to determine when iterations have completed.

{{#each thing in |things|}}
  {{measure-performance 'each thingy'}}
  
  {{thingy-component thing}}
{{/each}}

Will log the following to your console:

Avg iteration time for render thingy : 33ms (8 measurements)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment