Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Queue implementation memory leak? #106

Open
panta82 opened this issue Apr 10, 2015 · 0 comments
Open

Queue implementation memory leak? #106

panta82 opened this issue Apr 10, 2015 · 0 comments

Comments

@panta82
Copy link

panta82 commented Apr 10, 2015

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant