You should benchmark traversing an array of structs. In C and C++, you can access data directly, but in Java, you cannot. Expect a 10 times slow down in Java due to cache misses.
Unchecked pointer arithmetic, iterators and indexing are all pretty close to one another to even care about. Biggest difference is indexing looks much nicer and is easier to keep track of ( cleaner code ).
Yes, the importance of this cannot be overstated. Because of the prefetcher, data locality trumps all. It's why in C/C++ you're almost always better off to use an array of data structures rather than a linked list of data structures, even when doing lots of inserts and deletes. The cache misses inherent in following pointers swamps everything, even doing thousands of copies. In Java, almost everything is a pointer, so you are continuously getting cache misses, and can't take advantage of data locality the same way you can in C/C++.
It seems to me like the only time you would want to use an array over a list when doing lots of inserts and deletes is if the inserts and deletes are almost always at or very near the end of the array, otherwise you'd have to be doing a lot of shifting around. Or does the prefetcher manage to overcome that penalty somehow?
True. But from my experience, inserts and deletes are most often at the very end of the array. Think stacks, and temporary string buffers used by a parser. BTW: this is a good guide to C++ containers: i.stack.imgur.com/G70oT.png. Mostly, I end up with std::vector, and then std::map (sorted dictionary). Then comes std::deque (BFS tree traversal). I almost never use std::list.
in Gary's comparison between C and Java, he was only comparing between the relative performance between the two. However, he did not compare the relative size of programs in memory. The foot print. And C has a much much smaller footprint than Java. And for some embedded systems memory footprint is a big factor, not just performance. That is why some embedded developers are sticking with C rather that migrating to Java.
The problem with these results is that all of them are very focused on just performing lots of math. In a real application, while these may make up a good amount of the code, you also have to deal with lots of allocations/freeing memory or processing strings, arrays, and other data structures that isn't reflected by raw math performance. With AOT (ahead-of-time) compilation (rather than JIT/just-in-time), ART can reduce a lot of the runtime bottlenecks (runtime type information can be removed, functions can be inlined, generic code can be specialized) in a way that still matches the device quite well. But the problem is that ART wouldn't be able to get rid of all your allocations or delay garbage collection to parts of the program where not much performance is needed on its own, and that's where C/C++ would help out a ton.
@@BrunodeSouzaLino Why do people like to say this? It's obviously not true - there are hundreds of machine instructions on most architectures and add and subtract are only two of them. If you're going to spout nonsense like this, why not go all the way and say that computers can ONLY add, since subtraction is just adding a negative number? Consider that no computer would be Turing complete without compare and jump instructions.
Also we would have to see what compilation flags where in use and if the machine code was as optimized as it could be, for math, his function might just be some operation where the result are not used afterward, if you compile in a debug flags mode, those will be compute, but if you use -O3 (in GCC wich is mostly the one I use) then most of your math function won't even be compiled because the results are not used afterwards and the compiler might even say "alright I don't need that function at all lets skip it." But I don't think that it's possible to compare generated assembly for both Java with ART and C.
@@RmDIrSudoSu There are very easy ways to make sure that the result of the computation is used (e.g. compute the sum of all of the computations). If this guy didn't do that it would demonstrate serious incompetence.
John with andorid 4.4 and before andorid 4.4, you are right. Java had many flaws on andorid. But its getting better with every os. Java kind of catching up lately. A little late but better than never
Every single Android device you can find on market runs 4 or 6 cores at a time, not more than that, the big.LITTLE arch is such that only one cluster is used at a time.
Yeah, but memory is meant to be used. You shouldn't be wasteful with it, of course, but if you're restricting your memory footprint without good reason you're probably doing your users a disservice. Also memory was rolled in to this test to a certain degree, as high memory usage was likely the cause of the 60% difference in performance for the 64bit 6.0 jvm in the first test, via the garbage collector. The second and third tests would have needed very little memory, and were consequently much faster (at least for 64bit 6.0).
@@jeffwells641 memory use shouldn't be needlessly restricted, but hogging extra because you can leads to bloat. Most users have more than one thing running at once, so lightweight is always better, all else equal
The optimization point can't be overstated. A skilled C programmer should be able to squeeze out a lot more performance because of the granular control over low level functions. However there's a lot more room to screw things up, too.
No, function level optimization is something that a Compiler can do better than you in most cases (especially when you have data about the program behaviour). Data structure optimization makes the largest difference
@@DoomTobi "in most cases" is a neat thing. I'm saying that, at the top end, a custom tweaked solution done by hand by somebody who knows what they're doing is going to be the best, most optimal solution. Is it going to be worth all that effort for a complicated mix of C and assembly that doesn't port easily? No, "in most cases" it's going to be more efficient to let a compiler or interpreter handle it. But for a situation where optimization is crucial, doing it by hand has a higher ceiling for performance.
I just like to say: People who believe in Java being faster than C are about the same people who believe in moto-perpetual machines. j/k, but you got the point ;-)
Java is not always faster than C but it can be because the JIT optimizer has more information at runtime than the AOT optimizer which has less information. Furthermore, in practice Java is often faster than C programs for the same amount of developer effort because it is much simpler for the developer to have Java run on multiple cores (which almost all CPUs now have). Consider the runtime of a program using the Java streams API to iterate over a dataset where utilizing all the cores is trivial whereas in C it is a lot more complex so people don't. Again, in practice and with the same developer effort (which is the constraint for commercial development which is time/cost constrained) Java is usually faster than C by nearly the number of cores you have due to Java's support for parallelism (both in its standard API and the fact the parallel garbage collector means the developer doesn't have to figure out ownership and resource release).
One has to be very careful with these micro-benchmarks. One thing to remember is that once the C compiler has run, the generated code is frozen for good. Dalvik and Art however, are adaptive in that they will look for "hot code paths" at runtime and try to optimize. For brute data processing, the C compiler will almost always come in first place - but Java can easily and automatically inline code across linkage boundaries (think libraries/components). In other words, to do Java justice here, one should compare a large C application vs. a large Java application (Visual Studio vs. IntelliJ comes to mind). Last but not least, you can not write an Android app using only C/C++ and the NDK; to interact with the operating-system you need Java!
+Casper Bang Came here to say this. But I don't think that comparing the run times of applications of any size is fair as Java always has the overhead of the JVM and its non-deterministic garbage collection.
+Casper Bang LLVM can optimize "hot code paths" as well. The c compiler clang uses llvm. This means that the c compiler can also do the same optimizations. I don't know what c compiler Android is using though, but most likely, you can use any arm compatible c compiler.
In fairness, he is limiting his talk to Android devices and compilers. Otherwise, yeah: Garbage collection eats more memory than manual memory management, and can sometimes spoil caches, as well. OTOH, Manual memory management schemes sometimes hiccough reworking the heap, also. Interpreted C (and similar languages) is a pretty interesting practice, though.. Finally, if performance is the one true god, let's write it all in COBOL - completely static memory and compile time binding only. No???
A good example of seeing this branching / hotpath optimization is looking at Graal JVM and the showcases they did (I think it was Graal Ruby vs. plain Ruby)
Try looking at modern C++. Many of us from the Stone Age hated C++ because it was very clunky and cludgy. It was also from a time when OOP was quite new to the general industry and no-one really knew how to use it well. (I looked at some of my old 20+ yo books the other day - no wonder I hated C++). Recent C++11,14,17 has drawn from the experiences of Java, etc, and become really nice languages (and I say this as a C enthusiast of 30+ years :) ). Oh, and macros are deprecated in modern C++ (I also despise them) :D Oh, and if you decide to investigate C++, go straight to Stroustrup. Had I done so 25 years ago, I might have had a different opinion of C++. He is an excellent writer and shows things clearly and sensibly.
I hate java (it's bad) there are so many files for a very simple thing and i have to put the same code more than 2 times in every file (when i get a iPhone im learning swift and eraseing all java codes from my brain).
He did not do any of this. This is just benching a few simple functions with only a few operations in each and not representative of real world software. C will always be faster when both versions are well optimized. The difference on certain tasks will be huge, but many tasks in Java will just see a constant lagging in speed when compared to C. The biggest influence is the programmer. Do stupid things like too much abstraction, too many objects or deep complexity by nesting unpredictable conditions or looping over them and you get crap performance. Data locality, access predictability and branch predictability are king and with C, a programmer can exert control over these things, with Java not as much.
This always seems to be the difference between Java programmers and C/C++ programmers. The C/C++ programmer actually understands hardware and how to write code to take advantage of it for speed boosts. Java programmers just write code and hope for the best.
You also may want to extend your benchmark to not only include calculation. For example, most UI based software systems create lists, sort lists, search lists (and hash maps), data transformation, like form validation, translation from one representation into another, and serialization and deserialization. BTW: nice video.
I think the work you've done here is great, very interesting looking at the difference in performance between the two. I'm a software developer and tester myself so I think I may be able to help shed some further light on this subject. I don't think this comparison - or any direct C to Java comparison - is going to really get at the meat of why C might yield far better performance than Java. The reason why is in my experience people who write in a Java mindset write code in a way that they wield these incredibly inefficient data structures around via instances of objects. Since C is not object oriented, the entire design and approach towards architecture will be handled differently in C. These differences in approach are where I have seen substantial gains in performance, rather than the specific language chosen. Even if the comparison were C++ versus Java, this concept would still be at work. For those who don't know, C++ is (over-simplified) object-oriented C. The reason is Java just makes it easy and convenient to carry around these huge memory intensive objects so programmers in Java tend to use this liberally where I have seen less of that behavior in C++. One can certainly argue why that is or is not, but I'm simply saying those are the patterns I've seen emerge in my experience (warning: small sample size :)). So, to sum it all up with a TLDR: It's certainly intriguing to explore this in a direct way, but the real world difference between the two has less to do with run time and more to do with Java programmer behaviors versus C programmer behaviors.
I am also a software developer and I just happened to work on both java and c++ we had lots of benchmarks to find when we should use c++ code vs java code, and while I can agree that java developers don't care about memory even thenm when doing the same code using the same way in c++ (all virtual bases, unneded polymorphism...) it is surprisingly faster, around 3x average which is why new development in java only happens on UI side, and this 3x is doing code like java in c++ which is not the way to go, once you optimize a little (moving things to vector, remove unnecesary polymorphism, add move constructors ... etc) we get much better numbers from 3x to 1000x with the average being around 15x , obviously this is hard to notice in microbenchmarks as the java jit optimizer enters and then the produced code has very little overhead. And this is before getting to memory, because memory improvements are HUGE and actually one of the main reasons the c++ code came into the question our application was consuming around 8GB base, after some time with java optimization, etc we got it down to 6GB, and using a transpiler to move some code to c++ (almost no performance improvement) it got to 3gb, now our codebase is even bigger and the app remains around 3GB usage and profilers show that most of that is from the java side of code
What this video tells you: - given a numeric program with preallocated float[], Java is as fast as C => Pure hot path VM overhead is low What it doesn't tell you: - Given a program that is coded in the style of the language, it's starting to look completely different. => The main source for overhead are programing paradigms Reasons, why Java is slower than C/C++: - it forces you to do memory allocations for small objects - No pass by reference/pass by value semantics - everything is a virtual function - no template based generic programming - generics force you into object boxing/unboxing for basic types - interface inheritance is a bit expensive, as it requires a hash map/small array search - plain data arrays lead to bad programming style - garbage collection. Bad if you need real-time guarantees, bit in general not as bad as many think. Reasons why even C/C++ are not optimal in terms of performance: - no real knowledge about memory aliasing - bad simd instruction usage, due to independent compiler optimization steps
@@welltypedwitch I'm not sure yet. I didn't have a deeper look into it, but it seems to have some very cool concepts. What worries me is the compile time on larger projects.
One thing worth to mention about Java programs is the advantage of the bitecode to use features of future architecture through the JVM, while in C/C++, you need to recompile to machine code in order to utilize the same features. So, unless you recompile your C/C++ software, that initial performance gap between Java and C/C++ will disappear or move in favor of Java if you swap CPU. That's actually a great feature many applications, like servers that need to swap hardware but still need to provide services 24/7 or even at home if you built your new PC and you just swapped the OS drive. So, if anything, with Java you can be sure that every time you run your program, the software will use all the features of your CPU to the fullest extent.
What about Java vs C++? Obviously C is faster than Java... that’s like asking if assembly is faster than C. Like what about some function that implements a lot of object oriented programming ran in Java vs C++?
Jason Michelson C++ is just C with OOP, still a ton faster than Java. Actually there is no reason to use Java nowadays except for Android development. Other than that, if you want an easy and OOP-oriented programming language as Java, you have C#
DoubleC yeah I know what C++/C# are I’m a software engineer for a fortune 500 company lmao. I was just saying that comparing C to Java isn’t really a good comparison because C is a lower-level language and inherently faster.
Jason Michelson Generally C programmers don't compare C with Java, it's Java enthusiasts who like to go all out and cross fingers on these videos to see if maybe Java can have a magical "spark". Worthless nonetheless.
DoubleC responds to Jason Michelson C++ is just C with OOP. This was may be true before 2011. But today the c++ community which uses the new paradigm never write a program with OOP paradigm. OOP is the base class of evil is obsolete is finished. Why should I write a class which I should have to override a function again and again. To day writing PostModern C++ is essential. You define the concepts. And the compiler writes every needed class for you. Static binding is the solution. The compiler knows how to optimize the the progrem written modern c++.
As Dalvik uses a just in time compiler, you need to adapt your way to measure performance. In the beginning the code is interpreted and then based on monitoring information optimized. Therefore, you have to run your benchmark multiple times (as you did) and throw away your time measurements of first 500 000 iterations of the functions (actual number depends on the number of cycles the optimizer needs).
You want to know the state all of the more then ten thousand switches of gcc. Yes this is right, i've seen a CPPCON talk that there are more then 10000 options. Thats the difference to Java.
With the right gcc compiler options, I can make any nearly equivalent processor appear to be faster than it's competitor. It is quite the money maker. Intel loves that shit.
Kudos for putting in the effort on testing all the different devices. The most interesting comparison would have been memory and resource management; but creating those kinds of tests and ensuring they are optimal from each language standpoint is really, really difficult.
@@becomepostal Looks like Swift compiler converts Swift code to LLVM IR and then it goes through LLVM optimizations. As a result Swift is compiled to highly optimized machine code. No Virtual Machines, no GC pauses, no BS. Because Swift is just another frontend language for LLVM the performance should be similar to Objective-C compiled by LLMV. BTW, LLVM is used in Android NDK. So, C/C++ code (.so libs) run fast on Android. But apps / UI is still non-LLVM Java/Kotlin.
Memory allocation is one of the things that can cause a straight-forward C program to run significantly slower than Java. Now, some would say that you could simply implement an equally efficient algorithm in C, but since Java GC-performance has been evolving over decades putting in a couple of hours more work in the C-coding might not yield the desired result. Also, efficient threading requires more effort to implement in C than in Java and with some Android mobile processors having up to 8 or 10 cores that´s a huge potential win for performance.
americanswan - Nice. I'm now holding out for the V30. Something I use everywhere is the IR blaster. Was very disappointed this was omitted from the G6, am hoping the V30 will include an IR blaster.
Java has been very fast in the last 10-15 years. I ported some complex Java code to C once. I had to optimize the C code for days and it was still slightly slower than the Java version. In C you have a chance to go really deep and use things like x86's vector operations. But to use that you have to design your code for those instructions. This is not what the average programmer will do and it cannot be done every time.
pretty much a spot-on evaluation of the situation. If you want to go into depth, c allows you to do a lot more, but what you get with java, out of the box, does pretty much anything you want with good results. just by porting a java-app to c, will not make it run miraculously faster...
In other words: "I'm an average Joe programmer who has about 0 experience with C, and therefore I blame the language", this is basically what you're admitting. I'm not a big fan of C because of its productivity issues, but trying to say some-language is faster than C or Assembly is just trying to prove the the earth and sun are equally flat. Don't juggle the truth, like saying a bazooka is a *weaker* weapon because there were no robberies in your neighborhood the last year with it, therefore handguns are more powerful. You can say that bazookas are less of a menace to society than handguns, that is correct, just don't push it beyond just because you like either bazookas, handguns, both or neither.
please get in to details I have read from sites and watch people talk a little bit about it on their video but they don't have any clue of what they are talking about. thank you again Gary, I've learned a lot from your videos.
And this is why apple can get away with a dual core processor. Everything is tightly controlled and the resulting code is highly optimized for that CPU. With android due to the variations of the OS/Hardware/SoC there is a lot of variations and getting the best optimizations is not easy. I wonder how the new Java will work after the Oracle Lawsuit.
You probably get such an impressive results on running some cryptographic primitives on android 6+ not because of improved java runtime but because this functions in java crypto api are probably intrinsic which means you call java api that actually calls compiled C code inside. It explains 3 percent difference on android 6 (where android keystore and hardware crypto was first introduced). Also as some guys have already noticed - comparing calculation operations is quite irrelevant. The real advantage of native code is its memory management. Try to iterate through a huge cycle that will include creating new java objects and the native C counterpart will become ridiculously faster
Nice job. Would probably be useful to let people know that ARM 32-bit doesn't have a divide instruction (integer nor float). Starting with ARM64, there are both. e.g. try to avoid doing divides on 32-bit ARM if you want fast code. A good alternative is to multiply by the inverse. Your benchmark also doesn't touch on another issue of Java versus C. In C you can use SIMD and special instructions with intrinsics. ARM64 has unique instructions for doing cryptographic operations (e.g. SHA1/AES/SHA256) that are MUCH faster than trying to do it in C/Java.
"Java is as fast as or even faster than C" not statistically shown. Also a language cannot be faster then another, because it's a language, depends how it's compiled or interpreted. Also, the way the C code was compiled was not mentioned, did they use -O3 if using gcc? Or Intel compiler or else? anyways, in real world, serious things implemented are in C or C++, including, Ironically, the JVM itself.
You did have that 20 years ago. Java is 21 years old, and even older languages like C and C++ had that feature too, but it was "include" that imported header files.
+Gary Sims C/CPP optimization used to be my expertise, comparison may have been skewed inadvertently: 1) C is extremely strict about you telling the compiler EXACTLY what to create, examples: a) If you did not tell the compiler that it may use intrinsic functions (unrelated to inline functions) it will use a generic sqrt function that is not allowed to use intel's SSE b) If we mention inline, it is also extremely important to allow the compiler to decide on inline, or explicitly use pragmas or other means to allow inlining - this is critical for timing c) A few things may be considered untouchable by the compiler, so I need to see your "maths" implementation as well to tell if such non-optimizable code should be changed 2) In fact, when you keep to some rules it is even easier to create optimizable programs in CPP than C due to C standard being very strict at times. 3) Not an android expert myself, but is timing done in exclusive mode? I don't just mean single-processing, I mean with the kernel not intervening at all. Otherwise we may be lowering the percentage gap due to adding a constant.
+Android Authority Critical addendum about the languages: While Java's garbage collection is non-deterministic and rules out Java for hard RT, the MAJOR performance hit comes from the dynamic ALLOCATION and not the release, in fact the most expensive action devs do REGULARLY is dynamic allocation: 1) Java, dyn alloc done a lot behind the scenes, hard to avoid, programmers almost always include hidden allocs 2) CPP - basically avoid STL containers in critical areas (including CPP11 containers), and you're good (while you're there avoid RTTI, but that's unrelated to alloc :) ). 3) C - you are always aware of allocations, but you are also indirectly given complete control of optimization, so you may cause the compiler to think you ask to not optimize some stuff.
But the comparison did not include heavy memory allocation and deallocations and pointer arithmetic which a plus point of c and it's where c excels compared to java
I prefer C++ as well. I learned Java first but after learning C++ and getting used to the control it gives, Java just pisses me off now. It feels like an overprotective parent is telling me what I can and can’t do. C++ lets me do whatever I want and learn from my own mistakes. It definitely made me a better programmer.
Bugs are a main issue for software companies and sadly, not every programmer is great. It is much easier to write bugs in C/C++ (pointers, memory management, etc.) than in 'overprotective' java. it's so popular because the language and it's surrounding tools enforce a readable and maintainable code style.
+Darrien Glasser agreed 👍 , i guess gary ignore why google prefere java than C , we're talkin about a market here and how wide the language's used , but we agree C is faster its obv its low level language
As a C programmer, I am kind of happy for Java devs.
7 ปีที่แล้ว
The last benchmark might be related to question on stackoverflow, where a user complained that his java code ran several times faster than C with the same algorithm. The best answer was "Java is often faster at doing nothing at all", which follows from the fact that it can do runtime optimization of the code, wheras C compiler can only do a static one. And this most significantly helps in situations, where the code obviously does nothing.
May be this the reason still C is better. C is doing their work for him host one time in life. But Java doing Everytime. They called this is platform independent, let's enjoy it who cares about nano second when built a big webapp. But these sha things scary in Java webapp
What about the executable size? I know this a 3-year-old video, but I would like to know the sizes of each if you still have the executables available to you.
@@pow9606 Isn't that Same since C is static and Take almost Equivalent Assembly like Instructions! So That's same! Since whole code gets converted to assembly first then Binary! While Java has Little bit of Dynamic Functionalities!
Cool test, however unfortunately in java, most developers allocate massive amounts of objects for the GC to collect. And every object is on the heap. So in real world situations, java is much slower.
Guy1524 stupid programmed java programs are way slower than great programmed C programs... The only thing is that if you program a C program stupidly then it probably won't work You can't really compare bad programmed programs of one language with good programmed ones of another
Yes I have seen this in an Android app I am writing that does some heavy processing, a lot of number crunching (creating 3D point clouds), however not just math, but also a lot of objects. The garbage collector goes crazy to keep up. It is much, much faster in C++ with little to no extra effort. The code is just as clean and readable in C++. The only difference is that C++ crashes harder when you make a mistake, and I have to make up for it by lots of debug printing to Logcat to figure out what is going on.
We used to write our backend code in c++ for both IOS and Android under linux. Then hook up to the UI with SWIG JNI and Objective C++. But it was cheaper to hire developers to do the same thing twice and no developers understands the C++ except one.
Did you warm up each test to let the JVM decide that the code needed to be compiled before actually making the measurement? That is, your code should look like testFunc(); results = time(testFunc). If you don't warm up, then (on many JVMs) the time you measure includes a period of interpreting the bytecode, which is pretty slow, for the first 10,000 or more iterations, plus the time to compile the byte code into machine code.
Correction: "long" is (curiously) 32-bit on most or all 32-bit C platforms (every one i've ever coded on), whereas "long long" is 64-bit but is not part of C89. There is no 100% portable standard for 64-bit integers in C89, though all compilers support long long except in strict C89 compatibility mode. C99 portably specifies 64-bit integers. For a citation see the C_data_types page on Wikipedia.
Java and subsequent higher languages are made to be a bit more "developer friendly" in the sense that when I write a program, I do not have to worry about memory management. The compiler and GC does it for me. Both C and Java have different reasons to exist. Java was developed for much better code portability and applications. C is basically when you want to interact with hardware or when you need blazing performance. C is basically the "hey man I trust you with what you are doing so I'll let you do it" language.
Do not want to be rude but I'm sure you are not a professional C programmer and you don't have a true understanding of C compiling process If you had the results would be diffrent.
To clarify: The performance difference actually doesn't have too much to do with the language. It has far, far more to do with the optimisations performed by both the programmer and the compiler / runtime environment. C is not inherently "faster" than Java - the best Java runtime will generally generate faster code than the worst C compiler.
But that also means that you are not that proficient with any one language. Knowing the programming language itself is basically the easy part. The C - like languages are really similar to one another. The problem is that you have to learn to use the whole platform / a bunch of frameworks which can be really different from one another.
I've tinkered around with visual C++ compilers on windows making them output assembly code. They seem to do some funny stuff with optimizations. Even going as far as completely breaking logic. And the thing is, that is ok, and actually makes sense. For example, you could write a program that adds 100 constant numbers together in a loop, then prints the result. Then if you look at the resulting assembly code, you see that the compiler has deduced that there is no need to do this loop, and has just plopped the sum in to be printed out where you would expect a for loop of some kind. Not to say that that is what happened here, but compilers are SMART. And they look further into the source code logic than you may think.
Sudarsshan Telangi Gary did another video comparing the performance of an iPhone to a modern Android phone. Spoiler alert: have some tissues close by if you're an Android fan.
Thank you. As Dev/Admin i knew the Background and was no java fan for decades. But java has come very far, i am impressed. Until android, java was always considered hogging mem and time, but with android / smartfones it received much love, because there is no better solution to run the same on different phone architectures. Stuff learned.
C# started as J++, which was Microsoft copying Java and hiring some smart dudes to make improvements to it. At one point, Sun Microsystems sued Microsoft (probably because they were asshurt) and Microsoft changed the name to C# to distance itself.
the comparison with the Android platform is not correct! you need to check the source code of the function you are using because the Math class in Android is written entirely in c ++. java used in android is not standard java
To wrap up: If you really need to run fast, use C, otherwise, Java is fine. And processing times can be masked with transitions and animations, so the UX isn't affected.
The advantage of C is memory management. Integer arithmetic should be nearly the same between C and Java, those huge differences are a bit surprising. But for a proper test, you should write a program that requires major memory management...like a minimax searcher that uses a redblack tree to keep track of passed states. And no using standard libraries (which in java are probably written in C or ASM anyway). You'll probably find the C program finishes before the java program can even barely start.
Generally Java developers are so annoying, their "valid points" are always invalid. A few notes to this video: - Yes C is not object oriented, but C++ is, and you can use that as an alternative to C. - Anything interpreted by a engine via. bytecode will never be as fast as running natively in machine code, which C / C++ gets compiled down to. - Even C# gets compiled down to machine code, Java needs to get with the program (Java does have JIT though). - If you want to use a secondary language more advanced languages are Lua and JavaScript. These two perform way faster than Java and are interpreted languages as well. These have fantastic memory management and garbage collection systems as well. - Uninstall Java if you havn't already, there are many known security flaws.
+Newb Programming Indeed, C++ is an OO language, I didn't go into that, as it isn't the main point of the video. Also C# doesn't get compiled to machine code, it also get compiled to an intermediate language called CIL.
+Gary Sims Thanks for that correction. According to Microsoft, CIL is basically like JIT but a Microsoft version... which would mean C# should run slower at the machine level, because we all know Microsoft, heh.
Glad you said that because .NET Core was introduced this year (well 2015, but not widely known), C# can now be compiled as if it were C and run on anything. Microsoft is really trying to spy on people from other operating systems so they're trying to give native support to developers just to prove Microsoft products are better. www.microsoft.com/net/core
Botondar I see what you are saying now. Java still needs middleware, .NET* Core does not. .NET Core is native on the operating system you compiled for, and yes it does need multiple compiles, but Visual Studio made that process autonomous with 1 button. .NET Core is more like C than Java.
Whether java run time is using JustInTime or AheadOfTime compiling. The fact that its compiled at run time means the compiler has the ultimate chance to tailor the code for the machine/situation at hand. To get the fastest C performance you would have to compile an optimised version for each machine. At least testing your java against C is a good way to check your java performance.
hi, i also want to do work on NDK for my research for my masters degree... but every time i check the results java threads are faster than the native threads... i work on api level 23 and android marshmallow... any advise...?
You should benchmark traversing an array of structs. In C and C++, you can access data directly, but in Java, you cannot. Expect a 10 times slow down in Java due to cache misses.
Unchecked pointer arithmetic, iterators and indexing are all pretty close to one another to even care about. Biggest difference is indexing looks much nicer and is easier to keep track of ( cleaner code ).
Yes, the importance of this cannot be overstated. Because of the prefetcher, data locality trumps all. It's why in C/C++ you're almost always better off to use an array of data structures rather than a linked list of data structures, even when doing lots of inserts and deletes. The cache misses inherent in following pointers swamps everything, even doing thousands of copies. In Java, almost everything is a pointer, so you are continuously getting cache misses, and can't take advantage of data locality the same way you can in C/C++.
so every 1 nanosecond on C and C++ is 10 nanoseconds on java?
It seems to me like the only time you would want to use an array over a list when doing lots of inserts and deletes is if the inserts and deletes are almost always at or very near the end of the array, otherwise you'd have to be doing a lot of shifting around.
Or does the prefetcher manage to overcome that penalty somehow?
True. But from my experience, inserts and deletes are most often at the very end of the array. Think stacks, and temporary string buffers used by a parser. BTW: this is a good guide to C++ containers: i.stack.imgur.com/G70oT.png. Mostly, I end up with std::vector, and then std::map (sorted dictionary). Then comes std::deque (BFS tree traversal). I almost never use std::list.
in Gary's comparison between C and Java, he was only comparing between the relative performance between the two.
However, he did not compare the relative size of programs in memory.
The foot print.
And C has a much much smaller footprint than Java.
And for some embedded systems memory footprint is a big factor,
not just performance.
That is why some embedded developers are sticking with C rather that migrating
to Java.
Yeah, and it's really easy to optimize c by looking at what the compiler poops out then fixing the code. Java not so much.
The problem with these results is that all of them are very focused on just performing lots of math. In a real application, while these may make up a good amount of the code, you also have to deal with lots of allocations/freeing memory or processing strings, arrays, and other data structures that isn't reflected by raw math performance. With AOT (ahead-of-time) compilation (rather than JIT/just-in-time), ART can reduce a lot of the runtime bottlenecks (runtime type information can be removed, functions can be inlined, generic code can be specialized) in a way that still matches the device quite well. But the problem is that ART wouldn't be able to get rid of all your allocations or delay garbage collection to parts of the program where not much performance is needed on its own, and that's where C/C++ would help out a ton.
When it comes to the most fundamental level, your computer/mobile is nothing more than a fancy calculator that only does addiction and subtraction.
@@BrunodeSouzaLino Why do people like to say this? It's obviously not true - there are hundreds of machine instructions on most architectures and add and subtract are only two of them. If you're going to spout nonsense like this, why not go all the way and say that computers can ONLY add, since subtraction is just adding a negative number?
Consider that no computer would be Turing complete without compare and jump instructions.
Also we would have to see what compilation flags where in use and if the machine code was as optimized as it could be, for math, his function might just be some operation where the result are not used afterward, if you compile in a debug flags mode, those will be compute, but if you use -O3 (in GCC wich is mostly the one I use) then most of your math function won't even be compiled because the results are not used afterwards and the compiler might even say "alright I don't need that function at all lets skip it." But I don't think that it's possible to compare generated assembly for both Java with ART and C.
@@RmDIrSudoSu There are very easy ways to make sure that the result of the computation is used (e.g. compute the sum of all of the computations). If this guy didn't do that it would demonstrate serious incompetence.
@@RmDIrSudoSu Also what is "Java with ART"?
I love it when Gary talks nerdy to me
Tem que ir com calma man
Eduardo said "pace that down dude"
asdfgl, o 'man' não precisava traduzir não, véi
@@Caracazz2 man dindnT need to translate man
This channel needs more "Gary explains" videos!
Totally agree 👍
yeah, he is amazing
Java is the reason why your phone needs umpteen bajillion cores just to be responsive.
John with andorid 4.4 and before andorid 4.4, you are right. Java had many flaws on andorid. But its getting better with every os. Java kind of catching up lately. A little late but better than never
@@melihcelik9797 4.1.1 too
@@melihcelik9797 It is catching up because hardware improved drastically.
no that's wrong, those are multiple cpus in one die, those many cores don't run at the same time, look it up.
Every single Android device you can find on market runs 4 or 6 cores at a time, not more than that, the big.LITTLE arch is such that only one cluster is used at a time.
Is it fair to estimate performance only by running time? I think memory usage should have been shown as well.
Yeah, overhead is a big factor. Requiring a full virtual machine, interpreter, etc not only impacts speed but also memory footprint, security, etc.
Yeah, but memory is meant to be used. You shouldn't be wasteful with it, of course, but if you're restricting your memory footprint without good reason you're probably doing your users a disservice.
Also memory was rolled in to this test to a certain degree, as high memory usage was likely the cause of the 60% difference in performance for the 64bit 6.0 jvm in the first test, via the garbage collector. The second and third tests would have needed very little memory, and were consequently much faster (at least for 64bit 6.0).
And also different technical things to like core usage and all
@@jeffwells641 memory use shouldn't be needlessly restricted, but hogging extra because you can leads to bloat. Most users have more than one thing running at once, so lightweight is always better, all else equal
check iphone with 1gb ram n android with 1gb ram
The optimization point can't be overstated. A skilled C programmer should be able to squeeze out a lot more performance because of the granular control over low level functions.
However there's a lot more room to screw things up, too.
No, function level optimization is something that a Compiler can do better than you in most cases (especially when you have data about the program behaviour). Data structure optimization makes the largest difference
@@DoomTobi "in most cases" is a neat thing.
I'm saying that, at the top end, a custom tweaked solution done by hand by somebody who knows what they're doing is going to be the best, most optimal solution.
Is it going to be worth all that effort for a complicated mix of C and assembly that doesn't port easily? No, "in most cases" it's going to be more efficient to let a compiler or interpreter handle it.
But for a situation where optimization is crucial, doing it by hand has a higher ceiling for performance.
Yeah C is "slightly" faster than Java :D
exactly my thoughts :)
java is also unstable,unreliable,too user friendly,and too slow
only 4 times.
@abcd efgh Binary is not a language, what are you talking about?
@@11_22_XX Well I mean, people do use FPGAs for performance reasons indeed.
I just like to say:
People who believe in Java being faster than C are about the same people who believe in moto-perpetual machines.
j/k, but you got the point ;-)
Java is not always faster than C but it can be because the JIT optimizer has more information at runtime than the AOT optimizer which has less information. Furthermore, in practice Java is often faster than C programs for the same amount of developer effort because it is much simpler for the developer to have Java run on multiple cores (which almost all CPUs now have). Consider the runtime of a program using the Java streams API to iterate over a dataset where utilizing all the cores is trivial whereas in C it is a lot more complex so people don't. Again, in practice and with the same developer effort (which is the constraint for commercial development which is time/cost constrained) Java is usually faster than C by nearly the number of cores you have due to Java's support for parallelism (both in its standard API and the fact the parallel garbage collector means the developer doesn't have to figure out ownership and resource release).
@@staubsauger2305 Java is faster than C because it uses a JVM written in............... C
Remember, the JVM, compiler, etc etc...... is written in C!
Michael Morris dear god, you’re saying this tongue in cheek, right? You don’t actual think it’s faster, do you?
@@ender2999 of course not!
One has to be very careful with these micro-benchmarks. One thing to remember is that once the C compiler has run, the generated code is frozen for good. Dalvik and Art however, are adaptive in that they will look for "hot code paths" at runtime and try to optimize. For brute data processing, the C compiler will almost always come in first place - but Java can easily and automatically inline code across linkage boundaries (think libraries/components). In other words, to do Java justice here, one should compare a large C application vs. a large Java application (Visual Studio vs. IntelliJ comes to mind). Last but not least, you can not write an Android app using only C/C++ and the NDK; to interact with the operating-system you need Java!
+Casper Bang Came here to say this. But I don't think that comparing the run times of applications of any size is fair as Java always has the overhead of the JVM and its non-deterministic garbage collection.
+Casper Bang LLVM can optimize "hot code paths" as well. The c compiler clang uses llvm. This means that the c compiler can also do the same optimizations. I don't know what c compiler Android is using though, but most likely, you can use any arm compatible c compiler.
In fairness, he is limiting his talk to Android devices and compilers. Otherwise, yeah: Garbage collection eats more memory than manual memory management, and can sometimes spoil caches, as well. OTOH, Manual memory management schemes sometimes hiccough reworking the heap, also.
Interpreted C (and similar languages) is a pretty interesting practice, though..
Finally, if performance is the one true god, let's write it all in COBOL - completely static memory and compile time binding only. No???
CLisp, anyone?
A good example of seeing this branching / hotpath optimization is looking at Graal JVM and the showcases they did (I think it was Graal Ruby vs. plain Ruby)
Anytime dealing with C as a student I think one word...pointers.
C, the language itself, imo is pretty simple. The hard part is to write good code with C
Grobee simple makes it elegant
C is pretty cool (I don't really like C++) but I despise macros
Try looking at modern C++. Many of us from the Stone Age hated C++ because it was very clunky and cludgy. It was also from a time when OOP was quite new to the general industry and no-one really knew how to use it well. (I looked at some of my old 20+ yo books the other day - no wonder I hated C++). Recent C++11,14,17 has drawn from the experiences of Java, etc, and become really nice languages (and I say this as a C enthusiast of 30+ years :) ). Oh, and macros are deprecated in modern C++ (I also despise them) :D Oh, and if you decide to investigate C++, go straight to Stroustrup. Had I done so 25 years ago, I might have had a different opinion of C++. He is an excellent writer and shows things clearly and sensibly.
I hate java (it's bad) there are so many files for a very simple thing and i have to put the same code more than 2 times in every file (when i get a iPhone im learning swift and eraseing all java codes from my brain).
Great video explanation of the speed difference between the two languages. Please make more like this!
He did not do any of this.
This is just benching a few simple functions with only a few operations in each and not representative of real world software.
C will always be faster when both versions are well optimized.
The difference on certain tasks will be huge, but many tasks in Java will just see a constant lagging in speed when compared to C.
The biggest influence is the programmer.
Do stupid things like too much abstraction, too many objects or deep complexity by nesting unpredictable conditions or looping over them and you get crap performance.
Data locality, access predictability and branch predictability are king and with C, a programmer can exert control over these things, with Java not as much.
This always seems to be the difference between Java programmers and C/C++ programmers. The C/C++ programmer actually understands hardware and how to write code to take advantage of it for speed boosts. Java programmers just write code and hope for the best.
C Compiler optimizations *do* exist, too!
Was the C code compiled with -O0, -O1, -O2, or -O3?
I think the NDK does not compile with GCC, maybe the compiler was at fault for the code not being so much faster.
@@TimeoutMegagameplays That's 200 iq play right there. Make the C compiler worse so more people will code Java!
@@ianzen lmaooooooooooooooooooooooooooooooooo
You also may want to extend your benchmark to not only include calculation. For example, most UI based software systems create lists, sort lists, search lists (and hash maps), data transformation, like form validation, translation from one representation into another, and serialization and deserialization. BTW: nice video.
*A good listen for Java Fanboys*
Obviously, I am a C++ fan. :(
I think the work you've done here is great, very interesting looking at the difference in performance between the two. I'm a software developer and tester myself so I think I may be able to help shed some further light on this subject.
I don't think this comparison - or any direct C to Java comparison - is going to really get at the meat of why C might yield far better performance than Java. The reason why is in my experience people who write in a Java mindset write code in a way that they wield these incredibly inefficient data structures around via instances of objects. Since C is not object oriented, the entire design and approach towards architecture will be handled differently in C. These differences in approach are where I have seen substantial gains in performance, rather than the specific language chosen.
Even if the comparison were C++ versus Java, this concept would still be at work. For those who don't know, C++ is (over-simplified) object-oriented C. The reason is Java just makes it easy and convenient to carry around these huge memory intensive objects so programmers in Java tend to use this liberally where I have seen less of that behavior in C++. One can certainly argue why that is or is not, but I'm simply saying those are the patterns I've seen emerge in my experience (warning: small sample size :)).
So, to sum it all up with a TLDR: It's certainly intriguing to explore this in a direct way, but the real world difference between the two has less to do with run time and more to do with Java programmer behaviors versus C programmer behaviors.
I am also a software developer and I just happened to work on both java and c++ we had lots of benchmarks to find when we should use c++ code vs java code, and while I can agree that java developers don't care about memory even thenm when doing the same code using the same way in c++ (all virtual bases, unneded polymorphism...) it is surprisingly faster, around 3x average which is why new development in java only happens on UI side, and this 3x is doing code like java in c++ which is not the way to go, once you optimize a little (moving things to vector, remove unnecesary polymorphism, add move constructors ... etc) we get much better numbers from 3x to 1000x with the average being around 15x , obviously this is hard to notice in microbenchmarks as the java jit optimizer enters and then the produced code has very little overhead.
And this is before getting to memory, because memory improvements are HUGE and actually one of the main reasons the c++ code came into the question our application was consuming around 8GB base, after some time with java optimization, etc we got it down to 6GB, and using a transpiler to move some code to c++ (almost no performance improvement) it got to 3gb, now our codebase is even bigger and the app remains around 3GB usage and profilers show that most of that is from the java side of code
Please tell me this guy doesn't have a watch on each hand.
He has a smart watch on one hand and a fitness tracker on the other.
MizerienCauciuc no one told him that they make apps for smart watches that are fitness trackers
No it's a static discharge band. All true computer nerds are required to wear one at all times.
One is running C and one is running Java
He's so fat he's in 2 time zones at any time.
What this video tells you:
- given a numeric program with preallocated float[], Java is as fast as C
=> Pure hot path VM overhead is low
What it doesn't tell you:
- Given a program that is coded in the style of the language, it's starting to look completely different.
=> The main source for overhead are programing paradigms
Reasons, why Java is slower than C/C++:
- it forces you to do memory allocations for small objects
- No pass by reference/pass by value semantics
- everything is a virtual function
- no template based generic programming
- generics force you into object boxing/unboxing for basic types
- interface inheritance is a bit expensive, as it requires a hash map/small array search
- plain data arrays lead to bad programming style
- garbage collection. Bad if you need real-time guarantees, bit in general not as bad as many think.
Reasons why even C/C++ are not optimal in terms of performance:
- no real knowledge about memory aliasing
- bad simd instruction usage, due to independent compiler optimization steps
Nice comment! If those are your criticisms, what do you think of Rust?
@@welltypedwitch I'm not sure yet. I didn't have a deeper look into it, but it seems to have some very cool concepts. What worries me is the compile time on larger projects.
Gary the explaining god
7/10 at most.
Please, do a revisit with the new Android Nougat!
And oreo! :)
@@mateusschembri2194 and pie! :)
And 10 lol
Gary's videos never disappoint. Keep them coming!
How many keep turning volume up just to ear what he's saying.
@Dennis Fluttershy Hear* typos are inevitable.
Yeah no one NOSE what he's saying.
@@gherbihicham8506 EYE see what you did there
One thing worth to mention about Java programs is the advantage of the bitecode to use features of future architecture through the JVM, while in C/C++, you need to recompile to machine code in order to utilize the same features. So, unless you recompile your C/C++ software, that initial performance gap between Java and C/C++ will disappear or move in favor of Java if you swap CPU. That's actually a great feature many applications, like servers that need to swap hardware but still need to provide services 24/7 or even at home if you built your new PC and you just swapped the OS drive. So, if anything, with Java you can be sure that every time you run your program, the software will use all the features of your CPU to the fullest extent.
What about Java vs C++? Obviously C is faster than Java... that’s like asking if assembly is faster than C.
Like what about some function that implements a lot of object oriented programming ran in Java vs C++?
Jason Michelson C++ is just C with OOP, still a ton faster than Java. Actually there is no reason to use Java nowadays except for Android development. Other than that, if you want an easy and OOP-oriented programming language as Java, you have C#
DoubleC yeah I know what C++/C# are I’m a software engineer for a fortune 500 company lmao. I was just saying that comparing C to Java isn’t really a good comparison because C is a lower-level language and inherently faster.
Jason Michelson Generally C programmers don't compare C with Java, it's Java enthusiasts who like to go all out and cross fingers on these videos to see if maybe Java can have a magical "spark". Worthless nonetheless.
DoubleC responds to Jason Michelson C++ is just C with OOP.
This was may be true before 2011. But today the c++ community which uses the new paradigm never write a program with OOP paradigm. OOP is the base class of evil is obsolete is finished. Why should I write a class which I should have to override a function again and again. To day writing PostModern C++ is essential. You define the concepts. And the compiler writes every needed class for you. Static binding is the solution. The compiler knows how to optimize the the progrem written modern c++.
C++ is slower than C, yet not by a lot. In speed: C > C++ > Java.
As Dalvik uses a just in time compiler, you need to adapt your way to measure performance. In the beginning the code is interpreted and then based on monitoring information optimized. Therefore, you have to run your benchmark multiple times (as you did) and throw away your time measurements of first 500 000 iterations of the functions (actual number depends on the number of cycles the optimizer needs).
What were your compilation flags for C
not mentioned.. -O -5 :D
-Slow
You want to know the state all of the more then ten thousand switches of gcc. Yes this is right, i've seen a CPPCON talk that there are more then 10000 options. Thats the difference to Java.
Lothar Scholz He only needs to show the options he set explicitly, because all others are defaulted (and therefore can be looked up) anyway.
With the right gcc compiler options, I can make any nearly equivalent processor appear to be faster than it's competitor. It is quite the money maker. Intel loves that shit.
When Java turns out to be faster than C doing math you'll have to realize something is broken. You can't amulate faster than machine code.
Awesome video and explanation!
Kudos for putting in the effort on testing all the different devices. The most interesting comparison would have been memory and resource management; but creating those kinds of tests and ensuring they are optimal from each language standpoint is really, really difficult.
This video explains why iOS apps were 3 times faster than Android apps on comparable hardware in the past when iOS developers used Objective C
Alexander Pivovarov Are you implying that Swift is slower than Objective-C ?
@@becomepostal Looks like Swift compiler converts Swift code to LLVM IR and then it goes through LLVM optimizations. As a result Swift is compiled to highly optimized machine code. No Virtual Machines, no GC pauses, no BS. Because Swift is just another frontend language for LLVM the performance should be similar to Objective-C compiled by LLMV.
BTW, LLVM is used in Android NDK. So, C/C++ code (.so libs) run fast on Android. But apps / UI is still non-LLVM Java/Kotlin.
That isn't how it works, it is much more complicated.
@@himanshnegi832 lmao? 😂
Please enlighten us
Memory allocation is one of the things that can cause a straight-forward C program to run significantly slower than Java. Now, some would say that you could simply implement an equally efficient algorithm in C, but since Java GC-performance has been evolving over decades putting in a couple of hours more work in the C-coding might not yield the desired result. Also, efficient threading requires more effort to implement in C than in Java and with some Android mobile processors having up to 8 or 10 cores that´s a huge potential win for performance.
Happy to be running Marshmallow on a 64bit 808. LG G4.
americanswan I love the G4! Fantastic handset. I'm now using a G5 as my daily driver, but still hold a place in my heart for the G4.
Andy Turfer :) I'm on a V20 now. Very nice.
americanswan - Nice. I'm now holding out for the V30. Something I use everywhere is the IR blaster. Was very disappointed this was omitted from the G6, am hoping the V30 will include an IR blaster.
I like the way you explain. Smooth and clear.
Java has been very fast in the last 10-15 years. I ported some complex Java code to C once. I had to optimize the C code for days and it was still slightly slower than the Java version. In C you have a chance to go really deep and use things like x86's vector operations. But to use that you have to design your code for those instructions. This is not what the average programmer will do and it cannot be done every time.
pretty much a spot-on evaluation of the situation. If you want to go into depth, c allows you to do a lot more, but what you get with java, out of the box, does pretty much anything you want with good results.
just by porting a java-app to c, will not make it run miraculously faster...
I am glad that you agree. The final goal of the porting was to run on the GPU, but that never happened.
In other words: "I'm an average Joe programmer who has about 0 experience with C, and therefore I blame the language", this is basically what you're admitting.
I'm not a big fan of C because of its productivity issues, but trying to say some-language is faster than C or Assembly is just trying to prove the the earth and sun are equally flat.
Don't juggle the truth, like saying a bazooka is a *weaker* weapon because there were no robberies in your neighborhood the last year with it, therefore handguns are more powerful.
You can say that bazookas are less of a menace to society than handguns, that is correct, just don't push it beyond just because you like either bazookas, handguns, both or neither.
please get in to details I have read from sites and watch people talk a little bit about it on their video but they don't have any clue of what they are talking about. thank you again Gary, I've learned a lot from your videos.
And this is why apple can get away with a dual core processor. Everything is tightly controlled and the resulting code is highly optimized for that CPU. With android due to the variations of the OS/Hardware/SoC there is a lot of variations and getting the best optimizations is not easy.
I wonder how the new Java will work after the Oracle Lawsuit.
+Z Vaper In enterprise world: Just fine. :)
google won the case...oracle cant do shit now
You probably get such an impressive results on running some cryptographic primitives on android 6+ not because of improved java runtime but because this functions in java crypto api are probably intrinsic which means you call java api that actually calls compiled C code inside. It explains 3 percent difference on android 6 (where android keystore and hardware crypto was first introduced).
Also as some guys have already noticed - comparing calculation operations is quite irrelevant. The real advantage of native code is its memory management. Try to iterate through a huge cycle that will include creating new java objects and the native C counterpart will become ridiculously faster
The difference is that C++ guys don't seek validation by comparisons to other languages through questionable benchmarks
yep, they grow neckbeards instead
We also have sandals and pony tails. Never forget that :)
Nice job. Would probably be useful to let people know that ARM 32-bit doesn't have a divide instruction (integer nor float). Starting with ARM64, there are both. e.g. try to avoid doing divides on 32-bit ARM if you want fast code. A good alternative is to multiply by the inverse. Your benchmark also doesn't touch on another issue of Java versus C. In C you can use SIMD and special instructions with intrinsics. ARM64 has unique instructions for doing cryptographic operations (e.g. SHA1/AES/SHA256) that are MUCH faster than trying to do it in C/Java.
"Java is as fast as or even faster than C" not statistically shown. Also a language cannot be faster then another, because it's a language, depends how it's compiled or interpreted. Also, the way the C code was compiled was not mentioned, did they use -O3 if using gcc? Or Intel compiler or else?
anyways, in real world, serious things implemented are in C or C++, including, Ironically, the JVM itself.
Arjun Pakrashi Exactly!
Excellent video! I'm about to get my degree in CS and this is consistent with everything I've learned in my foundation courses.
I come from QBasic to learn java... holy shit! So much stuff you can just "import"... imagine having that 20 years ago :/
keep up
You did have that 20 years ago. Java is 21 years old, and even older languages like C and C++ had that feature too, but it was "include" that imported header files.
I had hoped for you to tell me that earlier... :)
@Jason Lee
Lets be honest, including in C/C++ is not as straightforward.
Amir Abudubai What do you mean? If you mean "not as simple as" then yes, it's not.
+Gary Sims C/CPP optimization used to be my expertise, comparison may have been skewed inadvertently:
1) C is extremely strict about you telling the compiler EXACTLY what to create, examples:
a) If you did not tell the compiler that it may use intrinsic functions (unrelated to inline functions) it will use a generic sqrt function that is not allowed to use intel's SSE
b) If we mention inline, it is also extremely important to allow the compiler to decide on inline, or explicitly use pragmas or other means to allow inlining - this is critical for timing
c) A few things may be considered untouchable by the compiler, so I need to see your "maths" implementation as well to tell if such non-optimizable code should be changed
2) In fact, when you keep to some rules it is even easier to create optimizable programs in CPP than C due to C standard being very strict at times.
3) Not an android expert myself, but is timing done in exclusive mode? I don't just mean single-processing, I mean with the kernel not intervening at all. Otherwise we may be lowering the percentage gap due to adding a constant.
+Android Authority Critical addendum about the languages:
While Java's garbage collection is non-deterministic and rules out Java for hard RT, the MAJOR performance hit comes from the dynamic ALLOCATION and not the release, in fact the most expensive action devs do REGULARLY is dynamic allocation:
1) Java, dyn alloc done a lot behind the scenes, hard to avoid, programmers almost always include hidden allocs
2) CPP - basically avoid STL containers in critical areas (including CPP11 containers), and you're good (while you're there avoid RTTI, but that's unrelated to alloc :) ).
3) C - you are always aware of allocations, but you are also indirectly given complete control of optimization, so you may cause the compiler to think you ask to not optimize some stuff.
HI SeventyFive, which is better if i want to write a emulator(such as psp or nintendo nds) for android , java or c++ , thanks!!!
Gary - impressive, as always.
But the comparison did not include heavy memory allocation and deallocations and pointer arithmetic which a plus point of c and it's where c excels compared to java
I am a c++ programmer and I know a bit of java... I like C++ better but also like Java :)
I prefer C++ as well. I learned Java first but after learning C++ and getting used to the control it gives, Java just pisses me off now. It feels like an overprotective parent is telling me what I can and can’t do.
C++ lets me do whatever I want and learn from my own mistakes. It definitely made me a better programmer.
Bugs are a main issue for software companies and sadly, not every programmer is great. It is much easier to write bugs in C/C++ (pointers, memory management, etc.) than in 'overprotective' java.
it's so popular because the language and it's surrounding tools enforce a readable and maintainable code style.
Then you should stick to C# instead, for the best of both those worlds and often even better :)
@@Erlisch1337 Not really. Which best part of the world of C++ is C# inheriting? C# is basically Java.
Loved that you pointed out the difference between different processors and Android versions
alright this is for all us CS majors
+HERRO Ikr. Always so interesting.
I dunno, this is some pretty basic stuff. I feel like this is for any major.
+Darrien Glasser agreed 👍 , i guess gary ignore why google prefere java than C , we're talkin about a market here and how wide the language's used , but we agree C is faster its obv its low level language
undergraduates
But what if you are only a private?
Totally amazed by that amount of effort paid off by Gary and every guy in Android Authority to run this test!!
As a C programmer, I am kind of happy for Java devs.
The last benchmark might be related to question on stackoverflow, where a user complained that his java code ran several times faster than C with the same algorithm. The best answer was "Java is often faster at doing nothing at all", which follows from the fact that it can do runtime optimization of the code, wheras C compiler can only do a static one. And this most significantly helps in situations, where the code obviously does nothing.
TH-cam recommendations 2016/2017/2018: Nah
TH-cam recommendations 2019 (almost 2020): It is time
Ikr
May be this the reason still C is better. C is doing their work for him host one time in life. But Java doing Everytime. They called this is platform independent, let's enjoy it who cares about nano second when built a big webapp. But these sha things scary in Java webapp
Am I the only one who got very annoyed by "Object Orientated" >
No
I'm surprised so few comments on that. Makes him seem a no0b, which he clearly is not.
Java is more "Class Hell" than Object Oriented.
What is the difference in performance between a pure java program and a processing for android program?
love Gary videos😃
What about the executable size? I know this a 3-year-old video, but I would like to know the sizes of each if you still have the executables available to you.
Moral: C is faster than Java
C and Java are just text. They don’t do anything. It’s the compiler/implementation that actually create a computer program.
So?
Moral of the story is less instructions runs faster than more instructions... More instructions requires more power and juices the battery.
@@pow9606 Isn't that Same since C is static and Take almost Equivalent Assembly like Instructions! So That's same! Since whole code gets converted to assembly first then Binary! While Java has Little bit of Dynamic Functionalities!
@@jscorpio1987 They don't create the convert the Code to Equivalent Assembly then Binary....If you want to be more Precise!
Loved this one! Brilliant! Shout out to you for the efforts that you have put in!! Keep it up!
Cool test, however unfortunately in java, most developers allocate massive amounts of objects for the GC to collect. And every object is on the heap. So in real world situations, java is much slower.
Guy1524 stupid programmed java programs are way slower than great programmed C programs... The only thing is that if you program a C program stupidly then it probably won't work
You can't really compare bad programmed programs of one language with good programmed ones of another
Personally, I would rather have the app not work unless the developer is competent. Would filter out so much garbage.
Yes I have seen this in an Android app I am writing that does some heavy processing, a lot of number crunching (creating 3D point clouds), however not just math, but also a lot of objects. The garbage collector goes crazy to keep up. It is much, much faster in C++ with little to no extra effort. The code is just as clean and readable in C++. The only difference is that C++ crashes harder when you make a mistake, and I have to make up for it by lots of debug printing to Logcat to figure out what is going on.
We used to write our backend code in c++ for both IOS and Android under linux. Then hook up to the UI with SWIG JNI and Objective C++. But it was cheaper to hire developers to do the same thing twice and no developers understands the C++ except one.
The whole time watching this I was wondering: Isn't the Android API in Java anyway? And then I got to the end.
+Dexx the Duck :-)
Did you warm up each test to let the JVM decide that the code needed to be compiled before actually making the measurement? That is, your code should look like testFunc(); results = time(testFunc). If you don't warm up, then (on many JVMs) the time you measure includes a period of interpreting the bytecode, which is pretty slow, for the first 10,000 or more iterations, plus the time to compile the byte code into machine code.
Java/Kotlin are used to build UI and to assemble app components together. The actual heavy components are written in C/C++, compiled and linked to .so
i've been waiting this for years!
This is what I call "tech". Most "tech" channels on TH-cam are actually just channels that talk about accessories or user experience.
Correction: "long" is (curiously) 32-bit on most or all 32-bit C platforms (every one i've ever coded on), whereas "long long" is 64-bit but is not part of C89. There is no 100% portable standard for 64-bit integers in C89, though all compilers support long long except in strict C89 compatibility mode. C99 portably specifies 64-bit integers. For a citation see the C_data_types page on Wikipedia.
40 Java programmers disliked video
Java and subsequent higher languages are made to be a bit more "developer friendly" in the sense that when I write a program, I do not have to worry about memory management. The compiler and GC does it for me. Both C and Java have different reasons to exist. Java was developed for much better code portability and applications. C is basically when you want to interact with hardware or when you need blazing performance. C is basically the "hey man I trust you with what you are doing so I'll let you do it" language.
Do not want to be rude but I'm sure you are not a professional C programmer and you don't have a true understanding of C compiling process If you had the results would be diffrent.
To clarify: The performance difference actually doesn't have too much to do with the language. It has far, far more to do with the optimisations performed by both the programmer and the compiler / runtime environment.
C is not inherently "faster" than Java - the best Java runtime will generally generate faster code than the worst C compiler.
damn... im gonna ditch java and learn c++ instead.
GAO Xiang2
Java is very very good and popular, just ignore the stupid structure of Java. Learn Qt for C++.
if you want to be an Android developer learn Java
If you're a real programmer, you don't "ditch" languages. You produce programs based on which language is most PRACTICAL for that one.
But that also means that you are not that proficient with any one language. Knowing the programming language itself is basically the easy part. The C - like languages are really similar to one another. The problem is that you have to learn to use the whole platform / a bunch of frameworks which can be really different from one another.
"I'm gonna ditch fruit ninja and start playing dark souls for casual fun!"
I've tinkered around with visual C++ compilers on windows making them output assembly code. They seem to do some funny stuff with optimizations. Even going as far as completely breaking logic. And the thing is, that is ok, and actually makes sense. For example, you could write a program that adds 100 constant numbers together in a loop, then prints the result. Then if you look at the resulting assembly code, you see that the compiler has deduced that there is no need to do this loop, and has just plopped the sum in to be printed out where you would expect a for loop of some kind. Not to say that that is what happened here, but compilers are SMART. And they look further into the source code logic than you may think.
reason behind why iPhones are faster than any Android phone...
Sudarsshan Telangi Gary did another video comparing the performance of an iPhone to a modern Android phone. Spoiler alert: have some tissues close by if you're an Android fan.
Only if you're a gamer. And only the loading screens.
kriss2005 "gamer"😂😂
oneplus 5 is actually faster than any iphone
It is not the fault of Java. I've just got my 7.1.1 update and it seems really smooth.
Thank you.
As Dev/Admin i knew the Background and was no java fan for decades. But java has come very far, i am impressed. Until android, java was always considered hogging mem and time, but with android / smartfones it received much love, because there is no better solution to run the same on different phone architectures. Stuff learned.
_"Java is rather unique"_ ...except for a little known language called C#?
yeah... a little known language that came 5 years later...
C# started as J++, which was Microsoft copying Java and hiring some smart dudes to make improvements to it. At one point, Sun Microsystems sued Microsoft (probably because they were asshurt) and Microsoft changed the name to C# to distance itself.
the comparison with the Android platform is not correct! you need to check the source code of the function you are using because the Math class in Android is written entirely in c ++. java used in android is not standard java
Java faster than C, what a fairytale :-)
To wrap up: If you really need to run fast, use C, otherwise, Java is fine. And processing times can be masked with transitions and animations, so the UX isn't affected.
Jaaava
Haha same here
The advantage of C is memory management. Integer arithmetic should be nearly the same between C and Java, those huge differences are a bit surprising. But for a proper test, you should write a program that requires major memory management...like a minimax searcher that uses a redblack tree to keep track of passed states. And no using standard libraries (which in java are probably written in C or ASM anyway). You'll probably find the C program finishes before the java program can even barely start.
Generally Java developers are so annoying, their "valid points" are always invalid.
A few notes to this video:
- Yes C is not object oriented, but C++ is, and you can use that as an alternative to C.
- Anything interpreted by a engine via. bytecode will never be as fast as running natively in machine code, which C / C++ gets compiled down to.
- Even C# gets compiled down to machine code, Java needs to get with the program (Java does have JIT though).
- If you want to use a secondary language more advanced languages are Lua and JavaScript. These two perform way faster than Java and are interpreted languages as well. These have fantastic memory management and garbage collection systems as well.
- Uninstall Java if you havn't already, there are many known security flaws.
+Newb Programming Indeed, C++ is an OO language, I didn't go into that, as it isn't the main point of the video. Also C# doesn't get compiled to machine code, it also get compiled to an intermediate language called CIL.
+Gary Sims
Thanks for that correction. According to Microsoft, CIL is basically like JIT but a Microsoft version... which would mean C# should run slower at the machine level, because we all know Microsoft, heh.
Glad you said that because .NET Core was introduced this year (well 2015, but not widely known), C# can now be compiled as if it were C and run on anything.
Microsoft is really trying to spy on people from other operating systems so they're trying to give native support to developers just to prove Microsoft products are better.
www.microsoft.com/net/core
C runs on anything UNIX (which is ran on just about everything we use).
Botondar
I see what you are saying now.
Java still needs middleware, .NET* Core does not.
.NET Core is native on the operating system you compiled for, and yes it does need multiple compiles, but Visual Studio made that process autonomous with 1 button.
.NET Core is more like C than Java.
One of the optimizations you could've done was used pointers!
I hate every language which contains J in it.
Java also!
Viorel I like one of them
-Japanese- / "Nippon" ✅
I bet you are poor in web programming cuz a website sucks without JavaScript
I also write web code, but C is my first love.
There is way to write Android program in C(or c++) without java?
h jtyj Android NDK
Lol did you just compare C to Java? Wtf 😂
Whether java run time is using JustInTime or AheadOfTime compiling. The fact that its compiled at run time means the compiler has the ultimate chance to tailor the code for the machine/situation at hand. To get the fastest C performance you would have to compile an optimised version for each machine. At least testing your java against C is a good way to check your java performance.
Americans- there is difference between c and java
British - thea i defe betwee c ai ava
Fantastic topic.
Excellent choices in case example specimen.
Good work!
Hang on a minute? Is the guy wearing *TWO* watches? I.e one on each hand.
Talk about dressing up like a complete dork...
L_A_G The watches could be set to different time zones
It looks more like a watch and a activity tracker .....
the other one is not a watch but a smartband
Wuww!!! That ahead of time, optimizing compiler is great!
And that's why iOS is faster than Android.
No.
Thiago Anderson Martins yeah, no wonder the $1000 iphone x loses to a $500 oneplus 5t in speed test . pfff
Objective C is not C
please do a comparison between C#and Java or something including C#
Just give us the results damn you
Both of my thumbs up for the research! and a very good presentation!
2:45 "with an attempt to *C* how much longer it takes in one language compared to another"
hi, i also want to do work on NDK for my research for my masters degree... but every time i check the results java threads are faster than the native threads... i work on api level 23 and android marshmallow... any advise...?
I like these types of videos. Great job A.A.!
Great video! Loving the FitBit/smartwatch combo. That's a pimpin' look in the tech world.