I have four classes. Apple, Orange, Mango and FruitIdentifier. First 3 classes have same properties ID and Price. I have a list of objects ( contains apple, orange and mango). I am iterating the list and based on the item type, creating FruitIdentifier instances and adding to a new list.
public class Apple
{
public int ID { get; set; }
public double Price { get; set; }
}
public class Orange
{
// props same as apple
}
public class Mango
{
// props same as apple
}
public class FruitIdentifier
{
public int ID { get; set; }
public double Price { get; set; }
public string Name { get; set; }
public FruitIdentifier (int id, double price, string name)
{
ID = id;
Price = price;
Name = name;
}
}
I am expecting a long list. My doubt is, before creating FruitIdentifier objects, I assign ID and Price properties to two variables and then passing those variables to FruitIdentifier constructor. Is there any performance improvement if I give the values directly inside the Constructor call.
List<object> fruitList = new List<object> (); // going to contains 1000s of items
List<FruitIdentifier> fruisIdentifiers = new List<FruitIdentifier> ();
foreach (var fruit in fruitList)
{
if (fruit is Apple apple)
{
apple.Price += 10;
var id = apple.ID;
var price = apple.Price;
fruisIdentifiers.Add(new FruitIdentifier (id, price, "Apple"));
}
if (fruit is Orange orange)
{
}
if (fruit is Mango mango)
{
}
}
// fruisIdentifiers.Add(new FruitIdentifier (apple.ID, apple.Price, "Apple"));
// like this. Any perfromance improvement ?
If you're looking for a performance improvement between:
var id = apple.ID;
var price = apple.Price;
fruisIdentifiers.Add(new FruitIdentifier (id, price, "Apple"));
and
fruisIdentifiers.Add(new FruitIdentifier (apple.ID, apple.Price, "Apple"));
It will be so negligable as to be non-existant. Don't prematurely optimize, and when you find your program is not performing, go looking for the real issues.
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.