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

18

u/DidYuhim Nov 04 '20

A lot of answers here, but I'll add my take.

Performance is a very complicated topic, so simplifying it to "C is faster than Java" is not very healthy. Usually, you want to compare specific pieces of code or implementations of algorithms to have a good discussion.

C programming language came about when a group of computer scientists got tired of writing Assembly instructions and created a program to do it for them. And since then, for most of it's uses, it remains what it was designed - a language that doesn't involve complex abstractions but relies on programmer to do their due diligence when working with it.

Java, on the other hand, was intended to "fix" the issues that C and C++ languages had: manual memory management, slow compilation times, a need to recompile entire project to target a new CPU architecture, standard library that forced you to depend on OS components during runtime, etc. Java attempts to fix a lot of those issues in the best way they knew at the time - but it had to make some trade-offs here and there.

C compilers had many years to mature into what they are right now. Modern C compilers are capable of optimizing a lot of common idioms into very efficient assembly - and assembly developers are aware of most common idioms.

Java developers live in a different world, however. Certain things are not allowed (in most cases, manual memory management) in regular Java programs. And since they are not allowed, the runtime can drop certain expensive checks during the execution and improve performance that way.

It's not useful to compare Java and C without concrete use-case or code sample.