Skip to content

Commit

Permalink
PERF: speed up breakUp
Browse files Browse the repository at this point in the history
breakUp function is complicated now, add a capped memoizer to ensure it runs a lot less.
  • Loading branch information
SamSaffron committed Dec 30, 2013
1 parent d8c43f7 commit 8ec887e
Showing 1 changed file with 46 additions and 1 deletion.
47 changes: 46 additions & 1 deletion app/assets/javascripts/discourse/lib/formatter.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,48 @@ Discourse.Formatter = (function(){
relativeAgeMedium, relativeAgeMediumSpan, longDate, toTitleCase,
shortDate, shortDateNoYear, tinyDateYear, breakUp;

/*
* memoize.js
* by @philogb and @addyosmani
* with further optimizations by @mathias
* and @DmitryBaranovsk
* perf tests: http://bit.ly/q3zpG3
* Released under an MIT license.
*
* modified with cap by Sam
*/
var cappedMemoize = function ( fn, max ) {
fn.maxMemoize = max;
fn.memoizeLength = 0;

return function () {
var args = Array.prototype.slice.call(arguments),
hash = "",
i = args.length;
currentArg = null;
while (i--) {
currentArg = args[i];
hash += (currentArg === Object(currentArg)) ?
JSON.stringify(currentArg) : currentArg;
if(!fn.memoize) {
fn.memoize = {};
}
}
if (hash in fn.memoize) {
return fn.memoize[hash];
} else {
fn.memoizeLength++;
if(fn.memoizeLength > max) {
fn.memoizeLength = 0;
fn.memoize = {};
}
var result = fn.apply(this, args);
fn.memoize[hash] = result;
return result;
}
};
};

breakUp = function(str, hint){
var rval = [];
var prev = str[0];
Expand Down Expand Up @@ -49,6 +91,8 @@ Discourse.Formatter = (function(){

};

breakUp = cappedMemoize(breakUp, 100);

shortDate = function(date){
return moment(date).shortDate();
};
Expand Down Expand Up @@ -240,6 +284,7 @@ Discourse.Formatter = (function(){
updateRelativeAge: updateRelativeAge,
toTitleCase: toTitleCase,
shortDate: shortDate,
breakUp: breakUp
breakUp: breakUp,
cappedMemoize: cappedMemoize
};
})();

0 comments on commit 8ec887e

Please sign in to comment.