I just don't get it. Why C is slower than Java?


  • 2
    L

    I'm familiar with C/C++, so most of my solution are written in C/C++.

    But why C is so much slower than Java now? Have you changed the judge compiler or something backend?

    I have three solutions in Java/C/C++ using the same algorithm, and the running time list below:

    Java 94 ms, C 204 ms, C++ 552 ms
    

    C code:

    int nthSuperUglyNumber(int n, int* primes, int primesSize) {
        if (n <= 0 || primesSize <= 0) return 1;
    
        int *index = (int *)calloc(primesSize, sizeof(int));
        int *nums = (int *)calloc(n, sizeof(int));
    
        nums[0] = 1;
        int storageIndex = 1;
    
        while (storageIndex < n) {
            int min = (1 << 31) - 1;
            for (int i = 0; i < primesSize; i++) {
                if (nums[index[i]] * primes[i] < min) {
                    min = nums[index[i]] * primes[i];
                }
            }
            nums[storageIndex++] = min;
            for (int i = 0; i < primesSize; i++) {
                if (nums[index[i]] * primes[i] == min) {
                    index[i]++;
                }
            }
        }
    
        int ans = nums[n - 1];
        free(index);
        free(nums);
    
        return ans;
    }
    

    Java Code:

    public class Solution {
        public int nthSuperUglyNumber(int n, int[] primes) {
            int k = primes.length;
            if (k == 0 || n <= 0) return 1;
            
            int[] index = new int[k];
            int[] nums = new int[n];
    
            nums[0] = 1;
            
            int i = 1;
            while (i < n) {
                int min = (1 << 31) - 1;
                for (int j = 0; j < k; j++) {
                    if (nums[index[j]] * primes[j] < min) {
                        min = nums[index[j]] * primes[j];
                    }
                }
                nums[i++] = min;
                for (int j = 0; j < k; j++) {
                    if (nums[index[j]] * primes[j] == min) {
                        index[j]++;
                    }
                }
            }
            
            return nums[n - 1];
        }
    }

  • 1
    S

    I also want to know, WHY???. In 116, my C code take 10ms while Java only need 5ms!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.