Is there any performance cost for declaring a new variable in the next case:
This is an example just to demonstrate the point.
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
And I have the next method:
Option 1:
public void MyMethod(Person person)
{
if (person.FirstName.Contains("Ro") || (person.LastName.StartsWith("A") && person.Age > 20))
{
//Do something
}
else if (person.FirstName.Contains("Ko") || (person.LastName.StartsWith("B") && person.Age >= 40))
{
//Do something
}
else if (person.FirstName.Contains("Mo") || (person.LastName.StartsWith("C") && person.Age > 60))
{
//Do something
}
else
{
//Do something
}
}
Option 2:
public void MyMethod(Person person)
{
string firstName = person.FirstName;
string lastName = person.LastName;
int age = person.Age;
if (firstName.Contains("Ro") || (lastName.StartsWith("A") && age > 20))
{
//Do something
}
else if (firstName.Contains("Ko") || (lastName.StartsWith("B") && age >= 40))
{
//Do something
}
else if (firstName.Contains("Mo") || (lastName.StartsWith("C") && age > 60))
{
//Do something
}
else
{
//Do something
}
}
Again, this is just an example to demonstrate the idea of the question.
The question: Is there any performance or memory issues between option 1 and option 2?
For sure, option 2 is looking better and is more readable.