TransWikia.com

Why is C is much slower as compared to Java?

Stack Overflow Asked by Jaysmito Mukherjee on February 3, 2021

So, I am completely new to C. I am testing the performance of the languages.

What I did?

I wrote 2 programs one in C one in java both doing the same thing but C is very slow as compared to Java?

Here are the programs:

main.c:

#include <stdio.h>
#include <time.h> 
#include <conio.h>

void work();

int main() {
    time_t seconds;     
    seconds = time(NULL); 
    printf("time1 : %ldn", seconds);
    work();
    seconds = time(NULL); 
    printf("time2 : %ldn", seconds);
    return 0;
}

void work() {
    int a[1000][500];
    for (int k = 0; k < 10000; ++k) {
        for (int i = 0; i < 1000; ++i) {
            for (int j = 0; j < 500; ++j) { 
                a[i][j] = (i + j) * 5416585;
            }
        }
    }
}

Main.java

public class Main {
    public static void main(String[] args) {
        System.out.println("time1 : " + (System.currentTimeMillis() / 1000));
        work();
        System.out.println("time2 : " + (System.currentTimeMillis() / 1000));
    }

    public static void work() {
        int a[][] = new int[1000][500];
        for (int k = 0; k < 10000; ++k) {
            for (int i = 0; i < 1000; ++i) {
                for (int j = 0; j < 500; ++j) { 
                    a[i][j] = (i + j) * 5416585;
                }
            }
        }
    }
}

My Question :-

So, my question is by all what I have read C should be much faster as it is low level whereas Java itself runs on a Virtual Machine thus should be comparatively slower! But in my case the outputs were : –

C:>gcc main.c

C:>javac Main.java

C:>a
time1 : 1610049457
time2 : 1610049468

C:>java Main
time1 : 1610049474
time2 : 1610049478

C:>a
time1 : 1610049487
time2 : 1610049498

C:>java Main
time1 : 1610049501
time2 : 1610049505

Clearly Java is much faster than C here!

Why is this happening?

One Answer

By default, GCC does not apply any optimizations, so the generated code is quite slow. In contrast, Java VMs enable most optimizations by default.

$ gcc main.c
$ time ./a.out 
time1 : 1610050160
time2 : 1610050167

real    0m7.113s
user    0m7.112s
sys 0m0.000s
$ gcc -O2 main.c
$ time ./a.out 
time1 : 1610050172
time2 : 1610050172

real    0m0.002s
user    0m0.002s
sys 0m0.000s

If you look at the generated assembler code, the body of the work function is optimized away in the optimized version:

work:
.LFB12:
    .cfi_startproc
    ret
    .cfi_endproc

Answered by Florian Weimer on February 3, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP