r/learnjava • u/IIwarrierII • 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 ?
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.
18
u/static_context Nov 03 '20
There are going to be a lot of people who can explain this better than me but...
Java is compiled to bytecode, which is interpreted by the virtual machine. It can be interpreted pretty damp fast, but it still needs to be converted from bytecode to machine code. I think this is called Just-In-Time compilation and is performed at run-time as the program executes.
C is compiled directly to machine code. So there are no additional runtime steps needed that might slow execution.
I think :).
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
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.
6
7
Nov 03 '20
I'm not a Java user, I despise oop gibberish with all my heart that being said the whole x is faster is a bs argument that fits a niche of developers that need to deliver near-metal performance (which btw doesnt even happen in best optimized videogames, best case scenario we speaking about specific algorithms) and developers who have no idea what are they talking about and most importantly wouldn't even know how to test bottlenecks.
There's people shoving complex Java applications since decades on computers that had a tiny amount of power compared even to a small cheap smarphone don't worry about this performance non sense. And in all that time compilation of Java made enormous steps forwards which alone make it faster. Just so you know btw, same algorithms running on the jvm and implemented in X have very low % differences.
Also don't listen to this whole "C is closer to the computer" thing, this ain't 1993 and the code a compiler written in the last 10 years gives you back is insanely different than what the programmer thought it would map and I'm not even accounting for the billions of optimizations at the isa and microcode level that basically make what you wrote have nothing to do on the machine level with what the code actually does.
2
u/Gixx Nov 04 '20 edited Nov 04 '20
See this timestamp on youtube interviewing Chris Lattner (creator of Swift and LLVM).
Lattner says, "I wanna write one program, and have it portable. This is something that assembly doesn't do."
So while you think C might be a god-tier language you need a compiler or thing that translates it to an architecture.
x86
ARM
RISC-V, ASIC
MIPS
I'm learning about it, and don't know a lot about low-level information.
x86 instruction sets can only be made by AMD and Intel. ARM can only be made by the company ARM (now sold to Nvidia).
To hear more above what I'm writing watch that entire youtube video (interesting timestamps: 572, 4000, 4538)
I'm also interested in performance. So I did 43 coding problems on Kattis.com in java. Now I've done 7 problems in Go.
Why is Go much faster than Java? Go compiles to a single binary, while java can run on any architecture that has a JRE installed. But kattis penalizes java because it includes the JVM startup time (the site does not say this, but the rank 17 guy (Bjørn Dons) told me Java should be just as fast as C++ if it didn't include the JVM load time).
A list of my memorable or interesting problems can be found here.
| problem | runtime Java (sec) | runtime Go (sec) |
|---|---|---|
| helpaphd | 0.15 | 0.02 |
| haypoints | 0.33 | 0.08 |
| heartrate | 0.35 | 0.08 |
| guessthedatastructure | 0.56 | 0.06 |
| goldbach2 | 0.53 | 0.08 |
| backspace | 0.23 | 0.10 |
| roundedbuttons | 0.79 | 0.10 |
2
u/llc_Cl Nov 04 '20 edited Nov 04 '20
Some might argue that Java is faster than C in some cases, because often times you can write the program so much faster. Let the processors do the rest - they’re fast enough.
But to understand why c is faster, I think you need to do some hardware programming. At least I did.
Maybe an analogy will work, because I don’t think I can explain it without one. It’s like in C you have more ability to customize how your programs interact with the specific hardware you’re running it on. Whereas Java just ‘translates’ or interprets the code for the given hardware.
Like if instead we substitute code with clothes, and speed with how those clothes fit. You’re going to get much better fitting clothes if they’re custom made, rather than getting some generic clothes that are ‘interpreted’ to fit you - like clothes from target or Walmart, say. Those clothes might be the right size, and work just fine. But if you needed clothes to reduce drag, like for a bicycle race, you would want a bicycle suit. I don’t think you can get a bicycle suit at Walmart or target. Even if you could, it probably wouldn’t fit well, defeating the purpose of trying to reduce drag. So, you probably wouldn’t buy that suit at a normal store, you would probably get it custom made.
Made a bunch of edits; sorry, writing on a cellphone.
2
u/J_Peanut Nov 04 '20
There are a lot of comments here explaining the differences between the compilation of Java and C - but I have found there are two aspects missing:
C is a language intended to be compiled directly to assembly. If you write code in C, you can predict how the generated assembly code will look. This allows programmers to optimise their code to a very high degree.
Benchmark programs are generally using C to measure the performance. They do this because C allows very specific interactions with the system and also because it has been established for that. Taking point 1. into account, it is possible to optimize systems to execute assembly generated by C. This is not the reason why C is fast, but one of the reasons why C runs just so good.
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.
1
u/GoodLifeWorkHard Nov 04 '20
It mostly has to do with memory management. Java has automatic garbage collection for dynamically allocated memory whereas C does not. So when you compile & run a Java program, it automatically scans the file to see which objects should be garbage collected. This increases the duration / length of time for Java. In C, you have to specify which dynamically allocated variables are deallocated otherwise you get a memory leak.
1
u/sowmyasri129 Nov 04 '20
C is a procedural, low level, and compiled language. Java is an object-oriented, high level, and interpreted language. Java uses objects, while C uses functions. Java is easier to learn and use because it's high level, while C can do more and perform faster because it's closer to machine code.
0
Nov 03 '20
[deleted]
6
u/IIwarrierII Nov 03 '20
Thanks for the explanation but what do you mean specifically by saying c can do more? Pointers allow C to do memory management manually compared to java’s garbage collector but in terms of capability did you mean speed and pointers ? Like what could be an example of something that java can’t do that c can if we get pass the pointers concept.
0
2
u/jonnycross10 Nov 04 '20
I really like how you phrased your last paragraph. You made it seem really bad ass haha
66
u/gtrley Nov 03 '20
Something along the lines of C is a lower level language and runs closer to the hardware, considering Java runs in the JVM