How to reduce memory taken up by a code?

how can one optimize the code in terms of memory? Reducing the variables used have no affect on it most of the times. At times codes using more variables take up less memory than mine using less. Can somebody explain. Thanks.

1 Like

Yes, one way to reduce memory is to use static allocation of memory rather than dynamic. I have experienced it in many of my codes. Allocating a memory to an array say in the starting of 100000 consumes 3.4 mb of memory while dynamic takes it upto say 9.7M or even 16.7MB depending upon the type the array is meant to store. Even the data structures like linked lists, hash tables, trees graphs have dynamic allocation of memory in the form of nodes, so they consume more memory, hash tables in particular! So avoiding allocation of dynamic memory is one way if u r really concerned with using less memory.

1 Like

thanks, i wastalking memory while running a code. even while using static variables i ve seen more memory shows up for a code with less variables .

Btw just came in mind, were you talking about the memory taken by the source code or the memory which your program takes while running :stuck_out_tongue: got confused, i guess. If u were talking about source codes, then you can go through the concept of macros simply add a line #define ll long long int below your include directives. And now instead of writing long long everytime u can just write ll. Just a small improvement. You can do the same for anything. for loops, cin, cout, anything.