From 0db86a95409f293a0995b13ec3e64f3baad3d2a4 Mon Sep 17 00:00:00 2001 From: Darren Date: Mon, 1 Dec 2014 12:46:11 +0000 Subject: [PATCH] Shave .7s from startup by caching member lookups in memberlist --- client/src/models/memberlist.js | 41 ++++++++++++++++++++++++++++++--- 1 file changed, 38 insertions(+), 3 deletions(-) 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 -- 2.25.1