1

Specifically how is compiled language able to better optimize the hardware compared to interpreted language? Other online sources that I have read only gave vague explanations like because it is written in the native code of the target machine while some do not even offer explanation at all. Would appreciate if the explanation provided can be as "Layman" as possible given that I've only just started to code.

Colin Seng
  • 39
  • 5
  • Machines can only execute assembly instructions. The program run can be yours (when compiled), or the interpreter, which in turn would run your code. There's a whole extra layer between your code and the machine, which takes time and memory to work properly. Such information can be easily found on Google or Wikipedia, though. – paulotorrens Apr 08 '17 at 13:20

1 Answers1

1

One major reason is optimizing compilers. Compiling "in advance" makes it much easier to apply optimizations to code, especially if you're compiling to native assembly code (as you typically do in C, for example). The fact that you know some stuff about the machine that it's going to be deployed on allows you to do machine-specific optimizations. This is especially important for, for example, Pentium-based processors, which have numerous complicated instructions that would tend to require some degree of knowledge of program structure in order to use (e.g. the MMX instruction set).

There are also some cases where the compiler can make structural changes to programs. For example, under special circumstances, some compilers can replace recursion with loops. (I once heard of someone writing a recursive Factorial function in C to learn about how to implement recursion in assembly language only to realize to his horror that the compiler had recognized an optimization and replaced his recursion with a for loop).

  • Pretty sure that story is from some SO user. Worth trying to dig it up! – Fureeish Jan 23 '19 at 08:43
  • 1
    @Fureeish It's from [this Meta post](https://softwareengineering.meta.stackexchange.com/questions/6166/open-letter-to-students-with-homework-problems) as a cautionary tale of why you shouldn't take shortcuts on homework assignments - the guy who did it ended up getting a 0 on the assignment because his solution wasn't recursive, and he struggled on the next assignment which assumed that you already knew how to do recursion in assembly language. – EJoshuaS - Stand with Ukraine Jan 23 '19 at 13:59