TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Suggestion: minification

Open RyanCavanaugh opened this issue 12 years ago • 193 comments

TypeScript should support emitting minified JavaScript.

There are several different things we could support:

  1. Just remove whitespace
  2. Minify unobservable identifiers
  3. Remove provably dead code
  4. Whole-program minification (i.e. closure compiler)
  5. (Others?)

RyanCavanaugh avatar Jul 15 '14 16:07 RyanCavanaugh

Whole-program minification (i.e. closure compiler)

Well... if you really want a reason to give up, here I go.

Let's use everyone's favorite function: a Fibonacci function, as an example!

Take this JavaScript Fibonacci implementation:

const sqrt5 = 5.0 ** 0.5;
const phi = (sqrt5 + 1.0) / 2.0;

export const fib = n => {
	const phi_pow = phi ** n;

	const fraction = -phi ** -n;

	return Math.floor((phi_pow + fraction) / sqrt5);
};

Maximally optimizing this would be illegal. This is a whole lot of instructions: multiple exponentiation operations, assignment ops, division ops, room for two ToPrimitive ops, subtraction, property lookups, function calls, addition ops, variable lookups, scope lookups, etc.

Take this input:

fib({
    [Symbol.toPrimitive]: () => {
        // ...
    }
});

This will cause these two lines to call the dreaded toPrimitive ops:

const phi_pow = phi ** n;

const fraction = -phi ** -n;

And that, is how you cause deoptimization to happen in any JS runtime :)

Honestly, I don't even want to put in the mental effort to optimize that.

Let's take the TS version:

type f64 = number;

const sqrt5: f64 = 5.0 ** 0.5;
const phi: f64 = (sqrt5 + 1.0) / 2.0;

export const fib = (n: f64): f64 => {
	const phi_pow: f64 = phi ** n;

	const fraction: f64 = -phi ** -n;

	return Math.floor((phi_pow + fraction) / sqrt5);
};

To start, we can perform constant folding on sqrt5 and phi:

const sqrt5: f64 = 2.23606797749979;
const phi: f64 = 1.618033988749895;

export const fib = (n: f64): f64 => {
	const phi_pow: f64 = phi ** n;

	const fraction: f64 = -phi ** -n;

	return Math.floor((phi_pow + fraction) / sqrt5);
};

Cool, let's inline those:

export const fib = (n: f64): f64 => {
	const phi_pow: f64 = 1.618033988749895 ** n;

	const fraction: f64 = -1.618033988749895 ** -n;

	return Math.floor((phi_pow + fraction) / 2.23606797749979);
};

Because the parameter n should always be a number, we can forget about those deopts that I had mentioned earlier, allowing us to do something tricky, like... rewriting those exponentiation operations:

const fraction: f64 = 1.0 / -1.618033988749895 ** n;

then move around the negation

const fraction: f64 = -1.0 / 1.618033988749895 ** n;

and then we can de-duplicate the entire exponentiation operation and variable lookup!

const fraction: f64 = -1.0 / phi_pow;

You know what? I'll skip the rest, no one cares about the process:

Here's the best that an advanced optimizing compiler could do that would be legal with TypeScript (note C compilers aren't even this good):

export const fib = (n: f64): f64 => Math.floor(
	1.0 / (n = 1.618033988749895 ** n) + n / 2.23606797749979
);

Go find me the minifier that can out perform that, I dare you. Closure compiler can't even do that with advanced optimizations.

Yet, it's not the best that it could be, performance-wise. We have an unnecessary lookup on the Math object.

Hoisting it, we would get this:

type f64 = number;

const { floor } = Math;

export const fib = (n: f64): f64 => floor(
	1.0 / (n = 1.618033988749895 ** n) + n / 2.23606797749979
);

~~Does anyone want to benchmark that func and compare it to AssemblyScript's hello world fib func to prove that plain TypeScript out-performs AssemblyScript?~~

That is my hand-optimized code for you, do you know how hard it would be to do this for every single line of code across my codebase? Stripping whitespace, the size of the text is 93 bytes. Equivalent Wasm would be 132 bytes, and most of it is just the Wasm header bytes. 39 byte difference; imho, it's not even worth it.

Of course, this is a trivial example, compiling entire web applications show much more major differences, but in the end, this is mistargeting JS as a compilation target, not to even talk about TS's any type and such, that create loopholes in the type system, effectively making it as good as JS anyway. TypeScript is not the right language to be minified+optimized, and JavaScript is a mediocre output target at best.

Allow any optimizations, and everyone will have different expectations for the degree that it should be optimized, ask me and I want that ^ level of optimization.

ghost avatar Jan 07 '21 03:01 ghost

Because the parameter n should always be a number, we can forget about those deopts that I had mentioned earlier, let's do something tricky, like... rewriting those exponentiation operations:

Btw rewriting C ** -y -> 1 / (C ** y) is illegal in general and will cause to precision lost. Only if C is power of two like 2.0, 4.0, 16.0 ... it may be possible but I'm not sure even in this case. That's why Closure Compiler, Prepack or LLVM / GCC never rewrite this as you proposed.

MaxGraey avatar Jan 07 '21 04:01 MaxGraey

Btw rewriting C ** -y -> 1 / (C ** y) is illegal in general and will cause to precision lost. Only if C is power of two like 2.0, 4.0, 16.0 ... it may be possible but I'm not sure even in this case. That's why Closure Compiler, Pprepack or LLVM / GCC newer rewrite this as you proposed.

Just to confirm, that "newer" was meant to be "never," right?

These are very valid concerns, no one wants to debug their code's mysterious precision loss, but it can help in very, very tightly executing code and reduce code size nonetheless, therefore we would have to put this under the suggested:

  1. (Others?)

it appears that we would need a --fast-math flag or something of the sort, further complicating TSC.

ghost avatar Jan 07 '21 14:01 ghost

Just to confirm, that "newer" was meant to be "never," right?

Yeah, just typo

MaxGraey avatar Jan 07 '21 14:01 MaxGraey

Because the parameter n should always be a number, we can forget about those deopts that I had mentioned earlier, let's do something tricky, like... rewriting those exponentiation operations:

Btw rewriting C ** -y -> 1 / (C ** y) is illegal in general and will cause to precision lost. Only if C is power of two like 2.0, 4.0, 16.0 ... it may be possible but I'm not sure even in this case. That's why Closure Compiler, Prepack or LLVM / GCC never rewrite this as you proposed.

Don't they do this with -Ofast? -Ofast allows applying the optimizations that may cause precision loss.

-Ofast Disregard strict standards compliance. -Ofast enables all -O3 optimizations. It also enables optimizations that are not valid for all standard-compliant programs. It turns on -ffast-math, -fallow-store-data-races and the Fortran-specific -fstack-arrays, unless -fmax-stack-var-size is specified, and -fno-protect-paren

aminya avatar Jan 07 '21 15:01 aminya

Yes, but it's not relate to -Oz (which is optimization for size). As I undersatand main goal of this proposal is minification but not optimize especially with loose some precision and potentially broke logic. So C ** -y -> 1 / (C ** y) in general case is not minify code, and may be shrink only if we have similar expression like C ** y in same scope which mean optimize should not only provide peephole optimizations but also provide more high level analysis like cost analysis, sophisticated matching expressions which more smarter than CSE (common sub-expression elimination). In this case TS will become compiler similar to LLVM, Ocaml or Go. I'm not sure this goal of TypeScript)

MaxGraey avatar Jan 07 '21 15:01 MaxGraey

Well, as discussed by other people, regarding the size optimizations, I am not convinced that TypeScript can do anything "much" different than what Terser and Closure Compiler are doing. Especially, when you can override things with any, as, and different projects may use different levels of strictness. You may able to use the types to apply some basic size reduction, but that is not going to be groundbreaking.

That's why I think a mixed target or a js-only target for AssemblyScript is a much better approach for applying "real" optimizations.

The goal of WebAssembly and ASM.js is exactly addressing what everyone wants. "Small and fast" code. For a JS developer, the easiest way to get to that goal is to use AssemblyScript.

aminya avatar Jan 07 '21 15:01 aminya

It would be nice if names of private properties and methods of a class would be minified/mangled by the typescript compiler. That is something what Terser or UglifyJS cannot do because after transpiling from TS to JS the "public/protected/private" information is lost.

SteffenAnders avatar Jan 07 '21 16:01 SteffenAnders

Don't they do this with -Ofast? -Ofast allows applying the optimizations that may cause precision loss.

-Ofast Disregard strict standards compliance. -Ofast enables all -O3 optimizations. It also enables optimizations that are not valid for all standard-compliant programs. It turns on -ffast-math, -fallow-store-data-races and the Fortran-specific -fstack-arrays, unless -fmax-stack-var-size is specified, and -fno-protect-paren

Ha, I doubt my Rustc has that type of flag. Sounds like it might, I'd have to check. Mathematically, that is, assuming infinite precision, the expressions are equivalent.

Yes, but it's not relate to -Oz (which is optimization for size).

In that particular case, it did shorten the size, but in general, it wouldn't even help.

... and may be shrink only if we have similar expression like C ** y in same scope...

That is precisely why I had done it there, if the expression were not there, I wouldn't have done it at all.

ghost avatar Jan 07 '21 16:01 ghost

It would be nice if names of private properties and methods of a class would be minified/mangled by the typescript compiler. That is something what Terser or UglifyJS cannot do because after transpiling from TS to JS the "public/protected/private" information is lost.

It can't be done anyway, the only reason to use private foo over #foo is to use it outside of the class, e.g. testing. Can't Terser/UglifyJS minify #foo in a class?

Does this suggest that using TS is actually worse for size than JS?

ghost avatar Jan 07 '21 16:01 ghost

Ha, I doubt my Rustc has that type of flag. Sounds like it might, I'd have to check.

No, it's can't. See this playground.

https://godbolt.org/z/GvY4Pd

As you can see in both cases (without and and with -ffast-math) LLVM generated two calls

MaxGraey avatar Jan 07 '21 17:01 MaxGraey

C++ uses exp2 instead of pow when Ofast is used instead of O3. https://godbolt.org/z/j676T5

aminya avatar Jan 07 '21 17:01 aminya

C++ uses exp2 instead of pow when Ofast is used instead of O3.

Yes, it's just minor performance optimization. JS Math hasn't Math.exp2(x, y) for example, but anyway it will be more code size than x ** y

MaxGraey avatar Jan 07 '21 17:01 MaxGraey

Yes, it's just minor performance optimization. JS Math hasn't Math.exp2(x, y) for example, but anyway it will be more code size than x ** y

In Wasm, these would both be equivalent in size:

local.get $x
local.get $y
call $Math::exp2
local.get $x
local.get $y
call $Math::pow

Which is really just debug info and can be

local.get 0
local.get 1
call 0

Allowing one to optimize Wasm for performance, without size costs, whereas using Math.exp2 in JS would cost two extra bytes per call, with a header size cost:

// const f = Math.exp2;
f(x,y);
x**y;

ghost avatar Jan 07 '21 17:01 ghost

In Wasm, these would both be equivalent in size:

Not really. Wasm hasn't builtin intrinsics for pow and exp2. That's why it call stdlib instead use something like f64.pow. It means code which use two call $Math::pow will be always smaller than code which call one call $Math::pow and one call $Math::exp instead and include implementations for pow and exp2 simultaneously

MaxGraey avatar Jan 07 '21 17:01 MaxGraey

This discussion seems to be veering pretty far off-topic; can we reel it in a bit please?

RyanCavanaugh avatar Jan 07 '21 17:01 RyanCavanaugh

There's a significant slice of JS/TS developers that don't care that much about bundle sizes, which contributes to the feeling some people have that JS/TS apps are bloated almost by definition.

It'd be amazing to see a critical player in the ecosystem like TypeScript taking a stance on this, offering an amazing minifier that leveraging the type system is able to deliver best in class minification ratios.

fabiospampinato avatar Jan 13 '21 13:01 fabiospampinato

TypeScript should support emitting minified JavaScript.

There are several different things we could support:

  1. Just remove whitespace
  2. Minify unobservable identifiers
  3. Remove provably dead code
  4. Whole-program minification (i.e. closure compiler)
  5. (Others?)

I would be happy with the easiest thing you could do (number 1)

We have a script that transpiles a separate repo right into our code base using an older version of ts, Theres is a MD file that says 'generated code do not edit' but it's easy to ignore that and forget. Having the simplest minification option would work far better at communicating to developers that this code is generated and not meant for editing.

Yes this can be done with additional tools and more lines in a script but a flag like "minifyWhitespace": true would be far nicer.

Ps. Props: If your transpiler didn't make code so readable I wouldn't need this

lonewarrior556 avatar Feb 18 '21 16:02 lonewarrior556

I would be happy with the easiest thing you could do (number 1)

I agree. Just removing whitespaces would decrease my .js sizes by 10%~20%. This could really be an option at the tsconfig that isn't hard at all to implement (they already exist!). Later more complex optimizations could be added, using other options at the tsconfig.

I don't think devs should necessarily use another tool for removing whitespaces. This is simple enough and a very very very common practice.

Edit: here is one of my .js compiled files:

😬

ftzi avatar Jul 24 '21 19:07 ftzi

I feel this discussion departs from the real reason this is important. Per Ryan's very early comment:

Motivating examples of things that TypeScript could minify but an external minifier could not would be useful. Things like closure and uglify do a really good job already; we'd have to have evidence we could make real improvements over them to justify spending time on it.

I think that really doesn't do justice for why this ticket is so important. It's important because it would save developer's time.

I saw this thread years ago. Why? Because one of my first use cases was "Damn, this product is sweet. Can't wait to minify with it. Let's google how to do that."

And I'm here now. Why? Because my first thought was "Sweet, I love this. Can't wait to minify it. Let's google how."

And this is ticket #8. Why? Because every other developer that uses this project thinks the same thing.

Yes, we COULD go download some additional third party software. But a lot of devs, like me, don't want to add yet another third party tool, don't want to learn another tool. We don't need it to be 10% faster than the alternative.

We just want it to be there because it's simple, it saves us time, and it makes our lives a lot easier. I'm finding myself baffled that this ticket still exists when it's such an otherwise amazing project with such a mind-boggling choice to not include this when MS is typically so good at designing for simplicity and user experience.

Scionax avatar Aug 22 '21 04:08 Scionax