Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

Commit 5aa55ab

Browse files
committed
perf($rootScope): improve watchers removal performance
Add a new id property to the watches Use this id when locating this id to remove the watch
1 parent c7ed8a3 commit 5aa55ab

File tree

1 file changed

+27
-3
lines changed

1 file changed

+27
-3
lines changed

src/ng/rootScope.js

+27-3
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ function $RootScopeProvider() {
7272
var $rootScopeMinErr = minErr('$rootScope');
7373
var lastDirtyWatch = null;
7474
var applyAsyncId = null;
75+
var watchId = 0;
7576

7677
this.digestTtl = function(value) {
7778
if (arguments.length) {
@@ -80,6 +81,10 @@ function $RootScopeProvider() {
8081
return TTL;
8182
};
8283

84+
function nextWatchId() {
85+
return ++watchId;
86+
}
87+
8388
function createChildScopeClass(parent) {
8489
function ChildScope() {
8590
this.$$watchers = this.$$nextSibling =
@@ -396,7 +401,8 @@ function $RootScopeProvider() {
396401
last: initWatchVal,
397402
get: get,
398403
exp: prettyPrintExpression || watchExp,
399-
eq: !!objectEquality
404+
eq: !!objectEquality,
405+
id: nextWatchId()
400406
};
401407

402408
lastDirtyWatch = null;
@@ -414,10 +420,12 @@ function $RootScopeProvider() {
414420
incrementWatchersCount(this, 1);
415421

416422
return function deregisterWatch() {
417-
if (arrayRemove(array, watcher) >= 0) {
423+
var index = binarySearch(array, watcher.id);
424+
if (index >= 0) {
425+
array.splice(index, 1);
418426
incrementWatchersCount(scope, -1);
427+
lastDirtyWatch = null;
419428
}
420-
lastDirtyWatch = null;
421429
};
422430
},
423431

@@ -1361,5 +1369,21 @@ function $RootScopeProvider() {
13611369
});
13621370
}
13631371
}
1372+
1373+
// Array is ordered in descending order by id
1374+
function binarySearch(array, id) {
1375+
var low = 0;
1376+
var mid;
1377+
var high = array.length - 1;
1378+
var value;
1379+
while (low <= high) {
1380+
mid = (low + high) >>> 1;
1381+
value = array[mid].id;
1382+
if (value > id) low = mid + 1;
1383+
else if (value < id) high = mid - 1;
1384+
else return mid;
1385+
}
1386+
return -(low + 1);
1387+
}
13641388
}];
13651389
}

0 commit comments

Comments
 (0)