简体   繁体   中英

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?

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.

Are you creating an instance variable of a type file in the first scenario? My prediction would be that this would require slightly more space than the bottom option. But as @DiskJunky pointed out, there is practically no difference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM