AngularJS Memory Leak Playground (Simple example)
Playground for detecting potential memory leaks when using AngularJS. Counting controller initializations and displaying memory usage. Memory leak!
by bjoerne
HTML
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular-route.js"></script>
<script type="text/ng-template" id="tab.html">
<p>Auto switching:
<button ng-click="startAutoSwitching()">start</button>
<button ng-click="stopAutoSwitching()">stop</button>
</p>
<p>Controller instantiations: {{controllerInstantiations}}</p>
<p>Heap size: {{heapSize}}</p>
<p>{{text}}</p>
</script>
<div class="main">
<ul class="menu">
<li><a href="#/this">This</a></li>
<li><a href="#/that">That</a></li>
</ul>
<ng-view></ng-view>
</div>
CSS
.main {
font-family: Helvetica, Arial, sans-serif;
font-size: 14px;
padding: 10px;
}
.menu {
margin-bottom: 10px;
}
.menu li {
display: inline;
}
p {
margin-bottom: 10px;
}
JavaScript
var app = angular.module('myApp', ['ngRoute']);
function heapSize() {
return Math.round(performance.memory.usedJSHeapSize / 10000, 2) / 100 + ' MB';
}
function text($rootScope) {
var result = ""
for (var i=0; i<100; i++) {
if ($rootScope.controllerInstantiations % 2 == 0) {
result += "AngularJS is an open-source JavaScript framework, maintained by Google, that assists with running single-page applications. Its goal is to augment web-based applications with model–view–controller (MVC) capability, in an effort to make both development and testing easier. The library reads in HTML that contains additional custom tag attributes; it then obeys the directives in those custom attributes, and binds input or output parts of the page to a model represented by standard JavaScript variables. The values of those JavaScript variables can be manually set, or retrieved from static or dynamic JSON resources. ";
} else {
result += "Model–view–controller (MVC) is a software pattern for implementing user interfaces. It divides a given software application into three interconnected parts, so as to separate internal representations of information from the ways that information is presented to or accepted from the user. The central component, the model, consists of application data, business rules, logic, and functions. A view can be any output representation of information, such as a chart or a diagram. Multiple views of the same information are possible, such as a bar chart for management and a tabular view for accountants. The third part, the controller, accepts input and converts it to commands for the model or view. ";
}
}
return result;
}
app.controller('ThisCtrl', function ($rootScope, $scope) {
$scope.controllerInstantiations = $rootScope.controllerInstantiations++;
$scope.heapSize = heapSize()
$scope.text = text($rootScope);
$rootScope.$on('someEvent', function() {
...