javascript-allonge icon indicating copy to clipboard operation
javascript-allonge copied to clipboard

Queue implementation memory leak?

Open panta82 opened this issue 10 years ago • 0 comments

I'm talking about the Queue implementation that is featured multiple times throughout the book.

var QueueMaker = function () {
    var queue = {
        array: [],
        head: 0,
        tail: -1,
        pushTail: function (value) {
            return queue.array[queue.tail += 1] = value
        },
        pullHead: function () {
            var value;
            if (queue.tail >= queue.head) {
                value = queue.array[queue.head];
                queue.array[queue.head] = void 0;
                queue.head += 1;
                return value
            }
        },
        isEmpty: function () {
            return queue.tail < queue.head
        }
    };
    return queue
};

The idea behind pullHead seems to be, instead of constantly splicing the array, just move the head pointer forward and delete the old element, creating a sparse array. Unfortunately, that's not what this line: queue.array[queue.head] = void 0; is doing. It just creates a reference to undefined and adds it to array.

What you probably wanted was this:

delete queue.array[queue.head];

Tested in Chrome like this:

q = QueueMaker();
function times(n, fn) { for (var i = 0; i < n; i++) fn(); }
function push() { q.pushTail(Math.random()); }
function pull() { q.pullHead(); }
function stress() { times(100, push); times(100, pull); }
setInterval(stress, 1);

In one tab, pasted the code above. In other, fixed with delete instead of assignment.

After ~ 15-20 minutes:

The first tab is the unpatched code.

panta82 avatar Apr 10 '15 21:04 panta82