Skip to content

Queue implementation memory leak? #106

Description

@panta82

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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions