Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the closure compiler create void 0 instead of shorter alternatives?

Comparing these strings:

{}[0]
[][0]
void 0

Why does Closure Compiler generate

void 0

when it could generate

[][0]

or

{}[0]

or even

[].a

as torazaburo mentioned which are 1 character shorter?

like image 227
trinalbadger587 Avatar asked Jan 03 '23 20:01

trinalbadger587


2 Answers

Minimum code size isn't the only goal of the Closure compiler. Another goal (I assume) is to generate code that is as fast as the original.

void 0 is likely to be faster across various JavaScript runtimes. It doesn't have to construct an object or array and dereference a nonexistent property.

A JavaScript runtime engine could possibly optimize away the {}[0] or [][0], but why would the Closure compiler want to depend on that? If those don't get optimized away, they would be significantly slower than void 0.

Keep in mind that JavaScript code is usually downloaded in compressed form, and if void 0 appears in multiple places they are likely to get compressed out.

Also see Blaise's answer for another good reason not to use {}[0] or [][0].

like image 170
Michael Geary Avatar answered Jan 06 '23 12:01

Michael Geary


{}[0] doesn't (always? see comments) return undefined, and [][0] could in theory return something other than undefined since you can override Array constructors/getters.

like image 27
Blaise Avatar answered Jan 06 '23 13:01

Blaise