Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rapidly creating new instances of Classes

Hypothetically the following situation:

one has to retrieve logfiles from a massive amount of folderstructures, and add these in a List.

Which scenario takes less resources from the machine?

LogFile file;
foreach (string filepath in folderfiles) 
{
   file = new LogFile { path = filepath, 
                        machine = machineName,
                        user = userName }; 
   files.Add(file);
}

or

foreach (string filepath in folderfiles) 
{
   LogFile logFile = new Logfile { path = filepath, 
                                   machine = machineName,
                                   user = userName }; 
   files.Add(file);
}

Would it even make any difference?

like image 226
MwBakker Avatar asked Dec 23 '22 13:12

MwBakker


1 Answers

In practice, the JIT (Just In Time) compiler would likely optimize away any differences between the two approaches. Conceptually, the first option is 'better' as the compiler (assuming no optimizations) would not have to worry about scope of the variable in the loop.

Also, the new instances created by new LogFile() will fall out of scope and be eligible for garbage collection about the same time for both approaches.

In short, no significant, if any, difference when fully compiled.

like image 161
DiskJunky Avatar answered Jan 09 '23 00:01

DiskJunky