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

Commit 358a69f

Browse files
committed
fix($rootScope): fix potential memory leak when removing scope listeners
When removing listeners they are removed from the array but the array size is not changed until the event is fired again. If the event is never fired but listeners are added/removed then the array will continue growing. By changing the listener removal to `delete` the array entry instead of setting it to `null` browsers can potentially deallocate the memory for the entry. Fixes #16135 Closes #16161
1 parent 417aefd commit 358a69f

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

src/ng/rootScope.js

+4-1
Original file line numberDiff line numberDiff line change
@@ -1207,7 +1207,10 @@ function $RootScopeProvider() {
12071207
return function() {
12081208
var indexOfListener = namedListeners.indexOf(listener);
12091209
if (indexOfListener !== -1) {
1210-
namedListeners[indexOfListener] = null;
1210+
// Use delete in the hope of the browser deallocating the memory for the array entry,
1211+
// while not shifting the array indexes of other listeners.
1212+
// See issue https://github.com/angular/angular.js/issues/16135
1213+
delete namedListeners[indexOfListener];
12111214
decrementListenerCount(self, 1, name);
12121215
}
12131216
};

test/ng/rootScopeSpec.js

+15
Original file line numberDiff line numberDiff line change
@@ -1903,6 +1903,21 @@ describe('Scope', function() {
19031903
}));
19041904

19051905

1906+
// See issue https://github.com/angular/angular.js/issues/16135
1907+
it('should deallocate the listener array entry', inject(function($rootScope) {
1908+
var remove1 = $rootScope.$on('abc', noop);
1909+
$rootScope.$on('abc', noop);
1910+
1911+
expect($rootScope.$$listeners['abc'].length).toBe(2);
1912+
expect(0 in $rootScope.$$listeners['abc']).toBe(true);
1913+
1914+
remove1();
1915+
1916+
expect($rootScope.$$listeners['abc'].length).toBe(2);
1917+
expect(0 in $rootScope.$$listeners['abc']).toBe(false);
1918+
}));
1919+
1920+
19061921
it('should call next listener after removing the current listener via its own handler', inject(function($rootScope) {
19071922
var listener1 = jasmine.createSpy('listener1').and.callFake(function() { remove1(); });
19081923
var remove1 = $rootScope.$on('abc', listener1);

0 commit comments

Comments
 (0)