Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could this code cause excessive memory usage?

Tags:

c#

I am investigating some code (written by someone else) to find what is causing memory usage to quickly increase to 8 GB. I'm not a true developer, more of a self-taught hobbyist that does some coding at work, so this is a bit over my head.

Could the following code, particularly creating a new object for lin on every iteration, cause memory to grow quickly? There are about 3 million records being processed. The data in each column is nothing extraordinary.

conn is a custom class.

SqlDataReader rdr = comm.ExecuteReader();
object[] lin = new object[17];

while (rdr.Read()){

    rdr.GetValues(lin);
    conn.Submit(lin, ref cmdString, ref recCount);
    lin = new object[17];

    }

I've seen some answers to memory-related questions about the garbage collector not being able to keep up. It seems to me that creating a new object in each iteration is unnecessary.

like image 805
Tony Hinkle Avatar asked Nov 19 '25 14:11

Tony Hinkle


1 Answers

It depends on how much Memory is available. Since the last Line of your loops body overwrites lin, no one seems hold a reference to it anymore. Only suspects would be rdr and conn, since they might keep one for no obvious reason. If they do not, it will get available for garbage collection which will take care of releasing the resources of the arrays you initialized when it is nessecary.

However, a cleaner solution could look like this, where the array gets cleared and reused instead of initializing a new one and overriding the old variable which used to hold the previous one.

var lin = new object[17];

while (rdr.Read()){
    rdr.GetValues(lin);
    conn.Submit(lin, ref cmdString, ref recCount);
    Array.Clear(lin, 0, 17);
}

Atlernatively, you could move the array-declaration into inner scope like i said in my comment:

while (rdr.Read()){
    var lin = new object[17];
    rdr.GetValues(lin);
    conn.Submit(lin, ref cmdString, ref recCount);
}

Im not sure on which of those solutions would be faster, but im sure you can figure it out by trial and error.

like image 129
nozzleman Avatar answered Nov 22 '25 04:11

nozzleman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!