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

2

u/ignotos Nov 04 '20 edited Nov 04 '20

In short - because Java does more "stuff" for you behind the scenes.

For example, if you access an array (someArray[i]) in C, it's really just accessing that array's memory. If 'i' is not a valid index, it's going to give you some junk value, or crash the program.

But in Java, it's first checking that 'i' is within the bounds of the array, and perhaps throwing an exception if 'i' is not a valid index.

Java is simply doing more work than C is in many situations. This is convenient for the programmer, and can help to avoid a lot of potential bugs, but there is inherently some overhead associated with this. C is more 'raw', and if you know what you are doing then you can write code which is more minimalistic, and avoids doing any work which isn't strictly necessary.