From: Darren Date: Mon, 1 Dec 2014 12:46:11 +0000 (+0000) Subject: Shave .7s from startup by caching member lookups in memberlist X-Git-Url: https://vcs.fsf.org/?a=commitdiff_plain;h=0db86a95409f293a0995b13ec3e64f3baad3d2a4;p=KiwiIRC.git Shave .7s from startup by caching member lookups in memberlist --- diff --git a/client/src/models/memberlist.js b/client/src/models/memberlist.js index 77beb06..41a6cde 100644 --- a/client/src/models/memberlist.js +++ b/client/src/models/memberlist.js @@ -47,13 +47,48 @@ _kiwi.model.MemberList = Backbone.Collection.extend({ return 0; } }, + + initialize: function (options) { this.view = new _kiwi.view.MemberList({"model": this}); + this.initNickCache(); + }, + + + /* + * Keep a reference to each member by the nick. Speeds up .getByNick() + * so it doesn't need to loop over every model for each nick lookup + */ + initNickCache: function() { + var that = this; + + this.nick_cache = Object.create(null); + + this.on('reset', function() { + this.nick_cache = Object.create(null); + + this.models.forEach(function(member) { + that.nick_cache[member.get('nick').toLowerCase()] = member; + }); + }); + + this.on('add', function(member) { + that.nick_cache[member.get('nick').toLowerCase()] = member; + }); + + this.on('remove', function(member) { + delete that.nick_cache[member.get('nick').toLowerCase()]; + }); + + this.on('change:nick', function(member) { + that.nick_cache[member.get('nick').toLowerCase()] = member; + delete that.nick_cache[member.previous('nick').toLowerCase()]; + }); }, + + getByNick: function (nick) { if (typeof nick !== 'string') return; - return this.find(function (m) { - return nick.toLowerCase() === m.get('nick').toLowerCase(); - }); + return this.nick_cache[nick.toLowerCase()]; } }); \ No newline at end of file