0

To achieve smooth animations in JavaScript, I have to avoid garbage collection. I was wondering, if the following "out-scoping" of the variable "key" would reduce garbage collection. The function "do" is called very often. In my example the variable "key" is kept alive after the function "do" terminates, but does this actually help?

define(function() {

    // keep reference to key to avoid garbage collection
    var key;

    function Test() {
        this.object = Object.create(null);
    }

    Test.prototype.do = function() {
        for (key in this.object) {
            this.object[key]++;
        }
    }

    return Test;

});

Furthermore articles always talk about avoiding string and object creation to reduce garbage, do integers not produce garbage too or is this just negligible?

EDIT: I think this is not a duplicate of this question, because I am asking specifically if it helps to out-scope a simple variable in a function and this has been asked, but not answered in the other question. Also the question about integers has not been answered.

Background information: this is about particles, to animate particles, I require many calculations for 1000 objects. All the objects are being reused so no garbage problem exists there, but within the function, many variables are created on every call.

Community
  • 1
  • 1
Toxiro
  • 528
  • 1
  • 3
  • 12
  • How have you determined that garbage collection is responsible for lack of "smoothness"? Inefficient DOM manipulation is generally much more likely to be the cause of jitter. – Pointy Oct 27 '16 at 12:04
  • The application uses canvas only, there is no DOM manipulation. I actually did not determine this, but read articles about this and it was always said to avoid garbage collection, is this not the case? – Toxiro Oct 27 '16 at 12:05
  • `Object.create(null);` It's this that will create garbage, not so much your `var key`.. If you can have you Object.create, cached then that would help. – Keith Oct 27 '16 at 12:08
  • Well, it would require many code contortions to fully avoid creating "garbage". It may be good practice to choose alternatives that involve less object creation. Your approach above doesn't make much sense to me however; it's not clear what it's trying to achieve. – Pointy Oct 27 '16 at 12:09
  • Object.create will only create one object in the constructor. The "key" variable will be called thousands of times in the function "do" and must be collected every time the function terminates. I want to avoid the thousands of variable initiations, but I am not sure, if this is achieved by this code. – Toxiro Oct 27 '16 at 13:44

0 Answers0