Elegant Function Timer Method Decorator in CoffeeScript
In this vain, I have struggled with the lack of a good pattern for decorating methods – doing things before, after, or around functions. For the Rubyist on Rails, you can think of the handiness of
ActionController’s filter methods and
Then I discovered Reginald Braithwaite’s awesome method decorators and combinators:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
Definitely read Reginald’s post for more of an overview on these. But for now, onto the practical example.
I’ve been mainly working on native-wrapped HTML5 mobile apps lately and I wanted a way to easily profile any function and log the milliseconds it takes to execute. It turns out I was able to do this as a small extension to
1 2 3 4 5 6
Give the timer a name and it applies an around filter to your returned function, which checks the difference between the milliseconds before and after the function call and prints it to the log. Your expected value of
this and any named arguments will be maintained in your decorated method. For example, say you wanted to profile how long it takes a Backbone View to render.
1 2 3 4 5 6 7
Easy peasy. This doesn’t account for deferred events like ajax callbacks, but it does let me analyze the client-side operations that I’m most interested in optimizing.