Skip to content
← Back to Community
How to make a code optimizer?
Profile icon

I'm looking for how to make a code optimizer.

Not a compiler, just an optimizer; ideally one that can be reused across different languages without much change. (I think that's impossible, but whatever)

I'm not sure if optimization / codegen is even taught anymore.

Generally, you'll hear not to prematurely optimize code, but a code optimizer can be used to improve performance while maintaining correctness.

Many compiled languages already have an optimizing compiler, ex: LLVM languages, Java, C#, Dart, etc.

But then there are languages that don't have any optimizations whatsoever, this is prevalent especially in interpreted languages.

I'm talking about a program that takes code like this:

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); };

and outputs stuff more like:

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

Not minified, but optimized.
Yet, I tried Google's closure compiler, and it had generated worse code.

That is only a trivial example. There are an infinite number of cases that could be optimized better.

I was thinking about making a compiled language but with the differences between different brands of compilers being so drastic, I was thinking that I would be better off making my own. (also, most optimizing compilers are designed to output a specific target, and can't be used on say, Python)

Does anyone know where I would start with automated code optimization?

Furthermore, would want to help make the optimizer?

Does anyone think that I would be better off just contributing to an open-source project like LLVM?

Profile icon
Profile icon
Profile icon

I think building from scratch up would be a very interesting learning experience!

However, I have never really attempted to make a code optimizer but it could be a very interesting experience! I don't know much, but I can perhaps take my knowledge I have gathered and work with you?

Profile icon

If I tried to build it 100% from Scratch wouldn't be great, since Scratch isn't even a programming language, c'mon.

Okay, but seriously, I feel like if I started from nothing and tried to figure it out on my own, I would need to refactor and backtrack a lot (more than I would've otherwise).

I don't even know about the different types of optimizers, the only one that I've ever heard of is a "peep-hole optimizer," and it's not great for whole program optimizations.

Profile icon

@xxpertHacker By "scratch" MocaCDeveloper means starting fresh, not the block coding language.

Profile icon

@DaCuteRaccoon I considered that to be obvious. Programming language doesn't matter, assuming we consider Scratch to be one.

Okay, but seriously...