简体   繁体   中英

How to prevent Google Closure Compiler from removing a line

I have a function where I create a test element. Before returning the function I'm nullifying the reference to the test element to help prevent a memory leak. But the closure compiler is removing that line b/c it thinks it's not needed (in both modes). Is there some kind of comment that I can add to prevent the line from being removed?

function isExample (testElem) {
 var bool; 
 testElem = testElem || document.createElement('div');

 // Do stuff in here to determine `bool`
 // ...

 // Then nullify the reference
 testElem = null; // The compiler removes this line. How do I make it keep it?

 return bool;
}

It is not needed. The garbage collector will do the same, so Google Closure Compiler just removes it.

I don't know of any garbage collector that leaks memory on this, JS would have pretty big problems if there were.

Remember that JS has function scope, which means that any variable defined in a function will be garbage collected once the execution gets out of the function.

This is one of the basic functions of the garbage collector, this'd be seriously bad if a js engine would leak memory on this.

For old IE leaks, you may try to work around the compiler by adding testElement = [] after nullifying it.

In this case, the compiler is correct. However, if you are dead set on keeping the code, then you'll need to use quoted syntax to either export the value or use a sink object.

function sinkValue(x) {
  sinkValue[' '](x);
  return x;
}
sinkValue[' '] = function(){};

function isExample (testElem) {
  var bool;
  var obj = { 'elem': testElem || document.createElement('div') };

  // Do stuff in here to determine `bool`
  // ...

  obj['elem'] = null;
  sinkValue(obj);

  return bool;
}

Quoted syntax prevents both renaming and dead-code elimination so you'll be negating any of those optimizations on that object property. In this case though you are extending the life of your object beyond the function (which seems to be the reverse of your intent).

There is no annotation to specify exactly what you want. You can see the discussions related to this at:

The compiler is doing exactly what is intended in that it is removing useless code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM