It appears that avoiding an explicit reference to a promise would prevent it from being forcibly allocated.
To test this theory, one could allocate numerous promises without resolving them:
var $q = angular.injector(["ng"]).get("$q");
setInterval(function () {
for (var i = 0; i < 100; i++) {
var $d = $q.defer();
$d.promise;
}
}, 10);
By monitoring the heap in Chrome profiling tools, we can observe the accumulation of memory needed to allocate 100 promises while maintaining less than 15 megabytes throughout the JSFIddle page.
Examining the $q
source code, there is no global reference to a specific promise, only connections from a promise to its callbacks. This demonstrates clear and concise coding practices. However, considerations should be made if a callback has a reference to the promise:
var $q = angular.injector(["ng"]).get("$q");
console.log($q);
setInterval(function () {
for (var i = 0; i < 10; i++) {
var $d = $q.defer();
(function ($d) { // loop closure thing
$d.promise.then(function () {
console.log($d);
});
})($d);
}
}, 10);
Following the initial allocation, the system seems capable of managing this scenario effectively :)
If allowed to run for a longer period, observing GC patterns in the last example reveals the cleanup process for these callbacks.
In summary, modern browsers handle unresolved promises efficiently as long as there are no external references tied to them.