Quickly create new class instances

Hypothetically the following situation:

you need to extract the log files from a huge number of folder structures and add them to the list.

Which scenario requires 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);
}

Doesn't that even matter?

+4
source share
2 answers

In practice, the JIT (Just In Time) compiler is likely to optimize any differences between the two approaches. Conceptually, the first option is “better”, since the compiler (in the absence of optimizations) should not have to worry about the scope of the variable in the loop.

In addition, new instances created new LogFile()will go out of scope and will be eligible for garbage collection at about the same time for both approaches.

, , , .

+8

? , , . , . , .

+1

Source: https://habr.com/ru/post/1686814/


All Articles