r/learnjava • • Nov 03 '20

Why is c faster than java?

If I were to make the same thing in java would it now be as fast ?

58 Upvotes

26 comments sorted by

View all comments

4

u/seanprefect Nov 03 '20

Ok here goes:

So there are levels to programming. At the most basic level the CPU runs instructions. Now the CPU takes instructions in the form of a binary number. so one number may add the following two numbers (I know about registers but i'm simplifying or else this would be a book) so this number thing is called machine code.

one level up is called assembly , now assembly is 1 to 1 with machine code except you use vaguely human readable instructions but they match exactly to the machine instructions.

Now computers need very exact instructions. So for example to add two numbers you might need 3 or 4 instructions, You can see how this becomes tedious.

One level above that you've got C. C lets you make one command (for example add) and it might be turned into several instructions. This is done by a compiler, which not only translates it to machine code but also optimizes it.

The thing is each operating system has it's own quirks and specifics so they wanted to make things able to run on many different systems. Unix is basically a way to make sure one program written in C can be re compiled on any other unix and run.

Well then what to do if you want to only ever compile once and not worry about the underlying processor and operating system. Well that becomes difficult.

Enter Java. With java you have the programs, but there's also something called the virtual machine. the virtual machine basically acts like the chip does in machine code. The java compilers compiles the program into something called bite code. Which is then fed into the virtual machine which then translates it into the specific processor/os machine code.

So there's this translation layer , from byte code to machine code. In many cases that introduces a significant speed penalty, but not always. You see if you have that real time translation, that means you can apply real time logic. So for example a program that handles many similar workloads (a web server for example) well that means java can pre-compute those jobs and be ready, and actually be faster than C. However in things like games, where you can't really logically pre compile it'll be slower.

I hope that makes sense.

2

u/nekokattt Nov 03 '20

technically assembly isn't always 1-to-1 with machine code, since many dialects like ARM have composite instructions like push and pop which actually translate to other instructions :-)

0

u/[deleted] Nov 03 '20

[deleted]

1

u/nekokattt Nov 03 '20

I'm a simple person, I see something that isnt true and I attempt to point it out.