structvsclass

CSharp · Console

/Program.cs

using System;
using System.Diagnostics;

public class PointControlA
{
	public double X
	{
		get;
		set;
	}

	public double Y
	{
		get;
		set;
	}

	public PointControlA(double x, double y)
	{
		X = x;
		Y = y;
	}
}

public class Point3ControlA : PointControlA
{
	public double Z
	{
		get;
		set;
	}

	public Point3ControlA(double x, double y, double z): base (x, y)
	{
		Z = z;
	}

	public static double Dot(Point3ControlA a, Point3ControlA b)
	{
		return a.X * b.X + a.Y * b.Y + a.Z * b.Z;
	}
}

public class Point3ControlB
{
	public double X
	{
		get;
		set;
	}

	public double Y
	{
		get;
		set;
	}

	public double Z
	{
		get;
		set;
	}

	public Point3ControlB(double x, double y, double z)
	{
		X = x;
		Y = y;
		Z = z;
	}

	public static double Dot(Point3ControlB a, Point3ControlB b)
	{
		return a.X * b.X + a.Y * b.Y + a.Z * b.Z;
	}
}

public struct Point3ControlC
{
	public double X
	{
		get;
		set;
	}

	public double Y
	{
		get;
		set;
	}

	public double Z
	{
		get;
		set;
	}

	public Point3ControlC(double x, double y, double z):this()
	{
		X = x;
		Y = y;
		Z = z;
	}

	public static double Dot(Point3ControlC a, Point3ControlC b)
	{
		return a.X * b.X + a.Y * b.Y + a.Z * b.Z;
	}
}

public class TestClassPerformance
{
}

public class Program
{
	public static void EyeshotIsSlow()
	{
		var vControlA = new Point3ControlA(11, 12, 13);
		var vControlB = new Point3ControlB(11, 12, 13);
		var vControlC = new Point3ControlC(11, 12, 13);
		var sw = Stopwatch.StartNew();
		var n = 10000000;
		double acc = 0;
		sw = Stopwatch.StartNew();
		for (int i = 0; i < n; i++)
		{
			acc += Point3ControlA.Dot(vControlA, vControlA);
		}

		Console.WriteLine("ControlA " + sw.ElapsedMilliseconds);
		acc = 0;
		sw = Stopwatch.StartNew();
		for (int i = 0; i < n; i++)
		{
			acc += Point3ControlB.Dot(vControlB, vControlB);
		}

		Console.WriteLine("ControlB " + sw.ElapsedMilliseconds);
		acc = 0;
		sw = Stopwatch.StartNew();
		for (int i = 0; i < n; i++)
		{
			acc += Point3ControlC.Dot(vControlC, vControlC);
		}

		Console.WriteLine("ControlC " + sw.ElapsedMilliseconds);
	}

	public static void Main()
	{
		EyeshotIsSlow();
	}
}
;