Shave .7s from startup by caching member lookups in memberlist
authorDarren <darren@darrenwhitlen.com>
Mon, 1 Dec 2014 12:46:11 +0000 (12:46 +0000)
committerDarren <darren@darrenwhitlen.com>
Mon, 1 Dec 2014 12:46:11 +0000 (12:46 +0000)
client/src/models/memberlist.js

index 77beb06a076a4e26aaceeae92294510f59b51379..41a6cdeb44e440f61e7d758ac5e24be674e3942b 100644 (file)
@@ -47,13 +47,48 @@ _kiwi.model.MemberList = Backbone.Collection.extend({
             return 0;\r
         }\r
     },\r
+\r
+\r
     initialize: function (options) {\r
         this.view = new _kiwi.view.MemberList({"model": this});\r
+        this.initNickCache();\r
+    },\r
+\r
+\r
+    /*\r
+     * Keep a reference to each member by the nick. Speeds up .getByNick()\r
+     * so it doesn't need to loop over every model for each nick lookup\r
+     */\r
+    initNickCache: function() {\r
+        var that = this;\r
+\r
+        this.nick_cache = Object.create(null);\r
+\r
+        this.on('reset', function() {\r
+            this.nick_cache = Object.create(null);\r
+\r
+            this.models.forEach(function(member) {\r
+                that.nick_cache[member.get('nick').toLowerCase()] = member;\r
+            });\r
+        });\r
+\r
+        this.on('add', function(member) {\r
+            that.nick_cache[member.get('nick').toLowerCase()] = member;\r
+        });\r
+\r
+        this.on('remove', function(member) {\r
+            delete that.nick_cache[member.get('nick').toLowerCase()];\r
+        });\r
+\r
+        this.on('change:nick', function(member) {\r
+            that.nick_cache[member.get('nick').toLowerCase()] = member;\r
+            delete that.nick_cache[member.previous('nick').toLowerCase()];\r
+        });\r
     },\r
+\r
+\r
     getByNick: function (nick) {\r
         if (typeof nick !== 'string') return;\r
-        return this.find(function (m) {\r
-            return nick.toLowerCase() === m.get('nick').toLowerCase();\r
-        });\r
+        return this.nick_cache[nick.toLowerCase()];\r
     }\r
 });
\ No newline at end of file