Продолжаем
собирать граблиАвтор: Sinix
Дата: 02.04.16
.
Что не так с методом
DoCore():
public interface ISomeInterface
{
int Do(int i);
}
// ...
public struct SomeStruct : ISomeInterface
{
public int Do(int i) => i + 1;
}
public struct SomeStruct2 : ISomeInterface
{
public int Do(int i) => i - 1;
}
// ...
public static int DoCore(this ISomeInterface x, int i) => x.Do(i);
и как его исправить?
| Подсказка |
| public interface ISomeInterface
{
int Do(int i);
}
// ...
public struct SomeStruct : ISomeInterface
{
public int Do(int i) => i + 1;
}
public struct SomeStruct2 : ISomeInterface
{
public int Do(int i) => i - 1;
}
// ...
private static int DoCore(this ISomeInterface x, int i) => x.Do(i);
public static void Main(string[] args)
{
Console.WindowWidth = 120;
const int Count = 100 * 1000 * 1000;
SomeStruct s = new SomeStruct();
Measure("DirectCall", () =>
{
for (int i = 0; i < Count; i++)
{
s.Do(i);
}
return Count;
});
Measure("ExtensionMethod", () =>
{
for (int i = 0; i < Count; i++)
{
s.DoCore(i);
}
return Count;
});
Console.WriteLine();
Console.WriteLine("Done.");
Console.ReadKey();
}
private static void Measure(string name, Func<long> callback)
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
var mem = GC.GetTotalMemory(true);
var gc00 = GC.CollectionCount(0);
var gc01 = GC.CollectionCount(1);
var gc02 = GC.CollectionCount(2);
var sw = Stopwatch.StartNew();
var result = callback();
sw.Stop();
var mem2 = GC.GetTotalMemory(false);
var gc10 = GC.CollectionCount(0);
var gc11 = GC.CollectionCount(1);
var gc12 = GC.CollectionCount(2);
var memDelta = (mem2 - mem) / 1024.0;
var gcDelta0 = gc10 - gc00;
var gcDelta1 = gc11 - gc01;
var gcDelta2 = gc12 - gc02;
Console.WriteLine(
"{0,20}: {1,5}ms, ips: {2,22:N} | Mem: {3,9:N2} kb, GC 0/1/2: {4}/{5}/{6} => {7,6}",
name, sw.ElapsedMilliseconds, result / sw.Elapsed.TotalSeconds, memDelta, gcDelta0, gcDelta1, gcDelta2, result);
}
|
| |