Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why i++ uses less memory than ++i while retaining same speed?

I was solving George And Accommodation and submitted two accepted versions of code with slight difference. Compiler used: GNU C++14

Version A (Time: 15ms, Memory: 4kb)

    #include <iostream>
    using namespace std;
     
    int main(){
        int n = 0, p = 0, q = 0, a = 0;
        cin >> n;
     
        while(n--){
            cin >> p >> q;
            if(q - p >= 2) a++;
        }
     
        cout << a;
        
        return 0;
    }

Version B (Time: 15ms, Memory: 8kb)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    #include <iostream>
    using namespace std;
     
    int main(){
        int n = 0, p = 0, q = 0, a = 0;
        cin >> n;
     
        while(n--){
            cin >> p >> q;
            if(q - p >= 2) ++a;
        }
     
        cout << a;
        
        return 0;
    }

I always thought ++a is faster and always use it in my loops. However, why does it require more memory while time being exactly the same? I know the general difference being one increments earlier, and one increments after.

>Solution :

This is just a random effect. It has no meaning.

The memory used is probably measured in pages, so the stack just happened to cross a page boundary in the second case. A page is typically 4kb.

Whether you use a++; or ++a; is completely irrelevant if a is a built-in type. The compiler will compile it to exactly the same machine instructions. It doesn’t matter which of these you use in a loop increment either. Neither is faster than the other or uses more memory than the other.

(Of course this is assuming you enable optimizations. Without optimizations enabled, there might be some weird effects, but measuring speed or memory without enabled optimizations is pointless.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading