I was testing the performance difference between reflection lib(e.g.fasterflect) against setting it manually. It is not surprising that reflection lib to be slower than manually set to value in code, however, on my laptop, following loop becomes much faster to run from second or third run:
var list = new List<ESG_MSCI_ClimateChange>();
///add 1million objects in the list first
for (int i = 0; i <= 1000000; i++)
{
var a = new ESG_MSCI_ClimateChange();
var b = (IExchangeForESG_MSCI_ClimateChange)a;
b.CarbonEmissionsEvicScope1Inten = (decimal)120;
b.CarbonEmissionsEvicScope2Inten = (decimal)120;
b.CarbonEmissionsScope12Fy20 = (decimal)120;
b.CarbonEmissionsScope12IndustryIntensity = (decimal)120;
b.CarbonEmissionsScope12Inten = (decimal)120;
b.CarbonEmissionsScope12Inten3yavg = (decimal)120;
b.CarbonEmissionsScope12IntenFy08 = (decimal)120;
b.CarbonEmissionsScope12IntenFy09 = (decimal)120;
b.CarbonEmissionsScope12IntenFy10 = (decimal)120;
list.Add(a);
}
////loop these one million objects 4 times and output time
for (var j = 0; j <= 3; j++)
{
Console.WriteLine("start!");
Stopwatch w = new Stopwatch();
w.Start();
foreach (var b in list)
{
b.CarbonEmissionsEvicScope1Inten = (decimal)120;
b.CarbonEmissionsEvicScope2Inten = (decimal)120;
b.CarbonEmissionsScope12Fy20 = (decimal)120;
b.CarbonEmissionsScope12IndustryIntensity = (decimal)120;
b.CarbonEmissionsScope12Inten = (decimal)120;
b.CarbonEmissionsScope12Inten3yavg = (decimal)120;
b.CarbonEmissionsScope12IntenFy08 = (decimal)120;
b.CarbonEmissionsScope12IntenFy09 = (decimal)120;
b.CarbonEmissionsScope12IntenFy10 = (decimal)120;
}
w.Stop();
Console.WriteLine($"took {w.ElapsedMilliseconds}ms to set");
}
What I see is that for the first loop always take much longer, and the second test and later run will be much faster. But why is that? If I use reflection to set the value, the time taken is fairly consistent(similar to the time taken in the first run).
So is c# caching the result somehow when set properties manually, so I shouldn't run this several times if I want to compare the performance between manual value setting and reflection (as in real world, we won't set the same list again and again)?
Aucun commentaire:
Enregistrer un commentaire