All I have heard so far are people who say that Java is generally slower than C, with a few exceptions (for example, using code that does nothing). So I went out to check it out. I had an array of 100,000 integers from 0 to 999,999. I used a double loop for a loop to sort them from the smallest to the largest, both in C and java (compiled on OS X).
The results were mostly completed in half the time. Of the 5 starts with different arrays, Java took about 17 seconds, and C took about 32 seconds (this includes allocating time and filling the array from a file, which was negligible for both).
So, what would make Java code faster than C? Is there something that I am missing, or some basic technology that I have not heard of?
Edit: Also not sure if this value matters, but I used it using the time command, not some custom code. Example:$time java SortArray
As for the compiler options, I cannot access this command line right now, but it was the default gcc option for OS X 10.10:
gcc sortarray.c -o sortarray
And I just used javac by default to compile Java.
javac SortArray.java
FROM
#include <stdio.h>
#include <stdlib.h>
#define SIZE 32
int main()
{
FILE* file = fopen("bigarray.txt", "r");
int arraySize = 100000;
int array[100000] = {};
int i, j, temp;
char inputBuffer[SIZE];
for (i = 0; i < arraySize; i++) {
fgets(inputBuffer, SIZE, file);
array[i] = strtod(inputBuffer, NULL);
}
for (i = 0; i < arraySize; i++)
for (j = i + 1; j < arraySize; j++)
if (array[i] > array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
for (i = 0; i < arraySize; i++)
printf("%d, ", array[i]);
return 0;
}
Java:
import java.io.*;
import java.util.Scanner;
public class SortArray {
public static void main(String[] args) throws IOException {
System.out.println("Hello world");
Scanner s = new Scanner(new File("bigarray.txt"));
int[] array = new int[100000];
for(int i=0; i<100000; i++) {
array[i] = s.nextInt();
}
for(int i=0; i<array.length; i++) {
for(int j=i+1; j<array.length; j++) {
if (array[i] > array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
for(int i=0; i<array.length; i++) {
System.out.print(array[i] + ", ");
}
}
}