Return early when calculating one-to-one room avatars

Object.keys() is O(n) and is wasted because we only care if the keys are 1 or 2.
Use `for .. in` instead and return early if there are >2 keys.

Profiling indicates this cuts wasted time from ~74ms to ~32ms for me (who has
a large number of rooms with large numbers of people in them).
This commit is contained in:
Kegan Dougal 2016-01-22 11:11:56 +00:00
parent e72323c405
commit f213901e29

View file

@ -67,14 +67,24 @@ module.exports = React.createClass({
}, },
getOneToOneAvatar: function(props) { getOneToOneAvatar: function(props) {
var userIds = Object.keys(props.room.currentState.members); var mlist = props.room.currentState.members;
var userIds = [];
// for .. in optimisation to return early if there are >2 keys
for (var uid in mlist) {
if (mlist.hasOwnProperty(uid)) {
userIds.push(uid);
}
if (userIds.length > 2) {
return null;
}
}
if (userIds.length == 2) { if (userIds.length == 2) {
var theOtherGuy = null; var theOtherGuy = null;
if (props.room.currentState.members[userIds[0]].userId == MatrixClientPeg.get().credentials.userId) { if (mlist[userIds[0]].userId == MatrixClientPeg.get().credentials.userId) {
theOtherGuy = props.room.currentState.members[userIds[1]]; theOtherGuy = mlist[userIds[1]];
} else { } else {
theOtherGuy = props.room.currentState.members[userIds[0]]; theOtherGuy = mlist[userIds[0]];
} }
return theOtherGuy.getAvatarUrl( return theOtherGuy.getAvatarUrl(
MatrixClientPeg.get().getHomeserverUrl(), MatrixClientPeg.get().getHomeserverUrl(),
@ -82,7 +92,7 @@ module.exports = React.createClass({
false false
); );
} else if (userIds.length == 1) { } else if (userIds.length == 1) {
return props.room.currentState.members[userIds[0]].getAvatarUrl( return mlist[userIds[0]].getAvatarUrl(
MatrixClientPeg.get().getHomeserverUrl(), MatrixClientPeg.get().getHomeserverUrl(),
props.width, props.height, props.resizeMethod, props.width, props.height, props.resizeMethod,
false false