Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory optimization in C for an array of 1 million records

I am writing a program which requires me to create an array of a million records. The array indices are unique ids(0-million represents unique product id). At first all elements are initialized to zero. They are incremented depending upon product sold.

This approach however has a high space complexity (4 * million bytes). Later I saw that only certain products need frequent updating. So is there any way in which I can reduce memory usage as well as keep track of all the products?

like image 596
Saurabh Avatar asked Dec 18 '25 03:12

Saurabh


1 Answers

If you don't need frequent updating then you can store all the results in a file. Whenever you are updating any entry you can just create a temp file with all the other entries plus the updated one. After that you can just change the name of the temp file using rename(temp,new);.

Although, an array of million records doesn't require that much memory(just 4 megabytes). So, your approach is the best and the easiest one.

The best approach(algorithmically) would be to make a hash table to store all the entries. But if you are not an expert in C then making a hash table could be a problem for you.

like image 152
fatrock92 Avatar answered Dec 19 '25 21:12

fatrock92