Skip to content

Commit

Permalink
fix($rootScope): fix potential memory leak when removing scope listeners
Browse files Browse the repository at this point in the history
When removing listeners the listener is removed from the array but the array size is not changed until the event is fired again. If that event is never fired but listeners are added/removed then this array will continue growing. This changes the listener removal to `delete` the array entry instead of setting it to `null` in the hope of the browser deallocating the memory for the array entry.

Fixes angular#16135
  • Loading branch information
jbedard committed Aug 9, 2017
1 parent 6b7505e commit b4fd43b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/ng/rootScope.js
Original file line number Diff line number Diff line change
Expand Up @@ -1180,7 +1180,10 @@ function $RootScopeProvider() {
return function() {
var indexOfListener = namedListeners.indexOf(listener);
if (indexOfListener !== -1) {
namedListeners[indexOfListener] = null;
// Use delete in the hope of the browser deallocating the memory for the array entry,
// while not shifting the array indexes of other listeners.
// See issue https://github.com/angular/angular.js/issues/16135
delete namedListeners[indexOfListener];
decrementListenerCount(self, 1, name);
}
};
Expand Down
15 changes: 15 additions & 0 deletions test/ng/rootScopeSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -2316,6 +2316,21 @@ describe('Scope', function() {
}));


// See issue https://github.com/angular/angular.js/issues/16135
it('should deallocate the listener array entry', inject(function($rootScope) {
var remove1 = $rootScope.$on('abc', noop);
$rootScope.$on('abc', noop);

expect($rootScope.$$listeners['abc'].length).toBe(2);
expect(0 in $rootScope.$$listeners['abc']).toBe(true);

remove1();

expect($rootScope.$$listeners['abc'].length).toBe(2);
expect(0 in $rootScope.$$listeners['abc']).toBe(false);
}));


it('should call next listener when removing current', inject(function($rootScope) {
var remove1 = $rootScope.$on('abc', function() { remove1() });

Expand Down

0 comments on commit b4fd43b

Please sign in to comment.