Say I was to have a method that required a small number of objects to be created during each run, and the method would be called multiple times, i.e. a method to delete a given row from a database. Would it be better to create a new object each time and call the Garbage Collector (or similar) to destroy it at the end, or reinitialise the value each time?
Example:
Using new constructors each time:
private void RemoveFolder(string dir)
{
OleDbCommand cmd2 = connection.CreateCommand();
OleDbParameter parameterC = new OleDbParameter();
cmd2.Parameters.Add(parameterC);
parameterC.Value = dir;
cmd2.CommandText = "DELETE * FROM [Directories] WHERE Path = ?";
cmd2.ExecuteNonQuery();
cmd2.Dispose();
}
Using a singular global variable (initialised within the constructor):
private void RemoveFolder(string dir)
{
parameterC.Value = dir;
cmd2.CommandText = "DELETE * FROM [Directories] WHERE Path = ?";
cmd2.ExecuteNonQuery();
}
EDIT: When I say better, I mean “as-a-whole” during normal non-“mission-critical” programs, where a large increase in performance would trump a minor decrease in stability.
EDIT2
An example of calling a similar method multiple times
(Note that this is for another method of mine, AddFolder)
foreach (DirectoryInfo directory in directories)
{
parameter.Value = directory.FullName;
cmd.CommandText = "SELECT LastModified FROM Directories WHERE Path = ?";
reader = cmd.ExecuteReader();
while (reader.Read())
{
output += reader.GetString(0);
}
if (output == null)
{
Console.WriteLine("New Directory! " + directory.FullName);
AddFolder(directory);
}
output = null;
reader.Close();
}
Your question is Do I need to optimize that code?
My opinion in general,
Otherwise if don’t sure if it will give an impact than leave it that way,
How to measure it?
You can see if your program is running to slow, or if it using to much memory..