Scope of variables: instantiation inside or outside

As part of the question I posted yesterday, it became clear that declaring a variable outside the loop and instantiating it inside does not have the performance benefit of simply moving the declaration inside the loop, so the declaration and instantiation are done at the same time, But what about creating an instance? Consider two options below.

//OPTION 1:
while (_doWork)
{
    Person p = new Person(name = "John", age = 35);
    //work that involves reading (not writing to) p
}

//OPTION 2:
Person p = new Person(name = "John", age = 35);
while (_doWork)
{
    //work that involves reading (not writing to) p
}

      

For the purposes of this question, the main assumptions are:

  • p is not required outside the loop
  • p is not written either (so the result is wise, the two are the same)
  • There is no reason why we should continue to re-create p (p looks the same in both cases)

Question . Which efficiency is better and which option is better?

The answer to this post (even though it is about declaration, not instantiation) seems to point to the latter: Declaring variables inside or outside of a loop

My thoughts:

  • It seems to me that it is a great loss for me to renew it. Maybe fine for primitive types, but for complex classes?
  • int a = 0 is the same as int a = new int (), so I guess the answer to this also applies to primitive types?
+3


source to share


2 answers


Which efficiency is better and which option is better?

As per your question, if only one instance is needed Person

, there is no logical reason to rerun it inside a loop. Select it once outside of your loop and use it internally.

With respect to the primitive types, you have to distinguish between value types ( int

, long

, double

), and a reference type ( string

). Value types are allocated on the stack, and reference types are allocated on the heap. Thus, just like for your class Person

, we will need to allocate the required number of bytes inside the heap, and allocation int

on the stack is faster allocation.

Apart from best practices, if you want to know which of the two has the best performance, compare your code. This is the output executed in Debug Mode

with .NET Framework 4.5, VS2013, on my Intel Core i5 M430:



public class Person
{
    public Person(string name, int age)
    {
        Age = age;
        Name = name;
    }

    public int Age { get; set; }
    public string Name { get; set; }
}

private static void Main(string[] args)
{
   Stopwatch sw = new Stopwatch();
   sw.Start();
   for (int i = 0; i < 1000000; i++)
   {
      Person p = new Person("John", 35);
      var age = p.Age;
      var name = p.Name;
   }

   Console.WriteLine("Loop with inner allocation took {0}", m sw.Elapsed);

   sw.Restart();
   Person px = new Person("John", 35);

   for (int i = 0; i < 1000000; i++)
   {
      var age = px.Age;
      var name = px.Name;
   }

   Console.WriteLine("Loop with outter allocation took {0}", sw.Elapsed)
}

      

And the results:

Loop with inner allocation took 00:00:00.0708861
Loop with outter allocation took 00:00:00.0155522

      

+3


source


If you do something 10 times less efficient than if you only do it once, then one copy is more efficient. It's also pointless to inject an object multiple times if you only need one instance. It can also have side effects that can make the situation worse.

So always declare and initialize it outside of the loop if it doesn't change in the loop. It will also increase readability, as everyone can see immediately that this object will most likely not change in the next cycle.

Person p = new Person("John", 35);
while (_doWork)
{
    //work that involves reading (not writing to) p
}

      



If you need to create an object in a loop, you must declare it in a loop. Not because it is more revealing, but more readable.

Read: https://softwareengineering.stackexchange.com/questions/56585/where-do-you-declare-variables-the-top-of-a-method-or-when-you-need-them

+1


source







All Articles