Why Java is running faster than C here?

后端 未结 9 709
甜味超标
甜味超标 2021-01-02 11:55

Inspired by this question,

Now visible only for users with > 10k rep

I came up with the following code:

$cat loop.c 
int main(          


        
相关标签:
9条回答
  • 2021-01-02 12:39

    Because the program doesn't do anything, an optimizer can remove the loop


    If you are trying to make a compiler do a certain unit or, well, benchmark of work, then you need to fool it into thinking the result of the work will actually be used.

    One way to do this is to write a function in one file, compile it, and then call it with the setup from another file. No compiler can anticipate what will be compiled in the future.

    Without that, it's just sort of a contest between default optimization levels and has no useful significance.

    0 讨论(0)
  • 2021-01-02 12:45

    Your program does absolutely nothing so this says nothing about the performance of both languages. The only thing it tells you is if your compiler is able to figure this out and therefore completely skips your program.

    To make it do "something" you would have to print every increment to stdout. If you print only the end result a good compiler could optimize your program to a statement that just prints this result and skips the whole "computation".

    0 讨论(0)
  • 2021-01-02 12:46

    There are some things you need to control for here:

    • the startup of the JVM is nontrivial compared to startup of a compiled C program
    • your loop isn't doing anything, and the compiler probably knows that
    • JIT compilers often produce better code than a non-optimised C compiler
    0 讨论(0)
提交回复
热议问题