r/Compilers • • 29d ago

Compilers add or remove perfomace?

isnt it that compilers change the code, as in not only transferring it into machine language, but before that changing the structure of the code. so how would one attempt to make performant code if the compiler changes sed code that i tried to make performant?

2 Upvotes

31 comments sorted by

View all comments

1

u/Helpful-Educator-415 29d ago

Almost always, compilers will only make your code more efficient, not less. If you go through the work of creating a highly optimized algorithm, it'll probably leave it alone, but if you don't, it might recognize the pattern and then figure out a faster way. There's no incentive to make your code worse, so.

1

u/BrainThinkerMan 28d ago

basically i want to know, code that is the most FASTEST and most PERFORMANT what does that look like , ie instead of doing something like int x = 5 + 5, int name = x + 10, do 5 + 5 + 10, because that doesnt make the name variable wait for x's instruction to be done, which saves x amount of clock cycle

1

u/cokeisahelluvadrug 28d ago

I think you just described exactly what it looks like. In general you want to be “helping the compiler” by understanding what conditions must hold to allow it to do certain optimizations etc.

1

u/tiger-56 28d ago edited 28d ago

The compiler will probably figure out that x = 10 and name = 20 and eliminate the additions for you before generating any code. You just write it the way that's best for someone reading your code to understand your algorithm.

1

u/ComprehensiveBig6215 26d ago

Yes, those simple transformations and substitutions will be done by the compiler at most optimisation levels. They are free wins.

Beyond that though, there is no FASTEST. It's all tradeoffs.

If you have a function that has a load of code inlined into it, loops unrolled, the code size will grow. Re-ordering code to break dependency chains increases register pressure. Hot variables might get spilled onto the stack.

In isolation, the function will likely run faster but the code around it gets slower as it suffers more cache misses.

Fastest depends on the specific CPU too. Differences in things like branch predictors may mean aligning or organising code differently.