Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

why programs like c and c++ use less storage than java programs

I am a college student and prefer java.I know core c. The problem is in many coding competition like codechef problem, spoj etc, most of the coder code in c++ which take storage of 2 or 3 MB comparatively 1400 MB in java. For Example storing two arrays of length pow(10,9), and then performing a certain operation based on the data collected in two arrays take vast memory in java. Is it possible to adopt any strategy to optimize the code? e.g.

Note: Constraint for value of 'n' : 1 ≤ N ≤ pow(10,9)

public void solve(InputReader in, PrintWriter out) {
    try {
        int n = in.nextInt();
        int k = in.nextInt();
        int[] time = new int[n];
        int[] profit = new int[n];
        int res = 0;
        int max = 0;
        for (int i = 0; i < n; i++) {
            time[i] = in.nextInt();
            profit[i] = in.nextInt();
        }
        for (int i = 1; i < n; i++) {
            double v1 = ((int) k / ((time[max]))) * (profit[max]);
            double v2 = (((int) k / ((time[i]))) * (profit[i]));
            if (v1 < v2) {
                max = i;
            }
        }

        res = ((int) k / time[max]) * profit[max];
        out.println(res);

    } catch (Exception ex) {
        return;
    }
}

EDITED 24 AUGUST 2017 It's an old question, however, I am adding more information now. Look at the picture below:

enter image description here

Here even on page 124 of 610 most successful answers are on the basis of languages like c or c++ as they acquire very less memory.

However, when I look into java solution, the memory acquired by them is pretty high.

java screenshot

As per the @Peter answer, it is clear that memory will be occupied in any language if we store it in an array of length pow(10,9)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Two arrays of 10^9 will use GBs of memory in any language. e.g. 2 * int[10^9] requires 8 GB of memory, whether you use C or Java.

The real solution is likely to be to not create the arrays at all as they don't appear to be needed. You can process the data as you read it. This will use next to no memory whether you use Java or C.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...