-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution8.cs
More file actions
49 lines (42 loc) · 1.5 KB
/
Solution8.cs
File metadata and controls
49 lines (42 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace cSharpSolutions
{
internal class Solution8
{
public struct PointStruct
{
public double X, Y;
public PointStruct(double x, double y) { X = x; Y = y; }
public double DistanceFromOrigin() => Math.Sqrt(X * X + Y * Y);
}
public class PointClass
{
public double X, Y;
public PointClass(double x, double y) { X = x; Y = y; }
public double DistanceFromOrigin() => Math.Sqrt(X * X + Y * Y);
}
public static void Run()
{
Console.WriteLine("=== Solution 8: Struct vs Class Performance ===");
const int iterations = 1000000;
var sw = Stopwatch.StartNew();
var pointsStruct = new PointStruct[iterations];
for (int i = 0; i < iterations; i++)
pointsStruct[i] = new PointStruct(i, i);
sw.Stop();
Console.WriteLine($"Struct allocation time: {sw.ElapsedMilliseconds} ms");
sw.Restart();
var pointsClass = new PointClass[iterations];
for (int i = 0; i < iterations; i++)
pointsClass[i] = new PointClass(i, i);
sw.Stop();
Console.WriteLine($"Class allocation time: {sw.ElapsedMilliseconds} ms");
Console.WriteLine("\nSolution 8 complete");
}
}
}