google / google/closure-compiler

How to optimize out constructors that do not (practically) have side effects?

Open
#3,185 3 comments 2 reactions 0 assignees View on GitHub
internal-issue-created triage-done
Dominant language
JavaScript
Stars
7.7k
Forks
1.2k
Avg merge
2d 12h
Merged PRs (30d)
6

Description

It looks like Closure does not optimize out redundant constructors that do not have side effects. Two such instances in my codebase are

```js
var a = new TextDecoder('utf8');
var buffer = new ArrayBuffer(1024);
var b = new Uint8Array(buffer);
```

in my codebase variables `a` and `b` are not used (but `buffer` is), so I would expect the above to optimize to

```js
var buffer = new ArrayBuffer(1024);
```

but instead it optimizes down to

```js
new TextDecoder('utf8');
var buffer = new ArrayBuffer(1024);
new Uint8Array(buffer);
```

i.e. Closure is thinking that the `TextDecoder` and `Uint8Array` constructors have side effects. (Technically they do, since they could `throw`, but I would very much like to treat them as if they never would)

I tried different annotations with

```
/** @nosideeffects */
function TextDecoder() {};
```

and

```
/** @nosideeffects */
var TextDecoder;
```

in my closure-externs.js file, but neither of those worked.

Is there a way to make Closure optimize out ctors that should be treated to not have any side effects? Or is the `@nosideeffects` annotation currently limited to not apply to constructors? (or perhaps my annotation syntax is wrong?)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.