Last active
March 5, 2024 16:10
-
-
Save GigaOrts/91d90bbaa0b06f0cdd6b6a90cfe697e5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Diagnostics; | |
class Prog | |
{ | |
static void Main(string[] args) | |
{ | |
Stopwatch stopwatch = new Stopwatch(); | |
ExampleStruct struct1 = new ExampleStruct(); | |
struct1.PrintSize(); | |
Console.WriteLine($"Передача значимого типа обычным способом (переменная копируется):"); | |
Console.WriteLine("---------------------------------------"); | |
stopwatch.Start(); | |
ExampleCopy(struct1); | |
stopwatch.Stop(); | |
Console.WriteLine($"{stopwatch.ElapsedMilliseconds} ms\n{stopwatch.ElapsedTicks} ticks\n"); | |
Console.WriteLine("---------------------------------------"); | |
Console.WriteLine($"Передача значимого типа без копирования:"); | |
Console.WriteLine("---------------------------------------"); | |
stopwatch.Restart(); | |
ExampleRef(in struct1); | |
stopwatch.Stop(); | |
Console.WriteLine($"{stopwatch.ElapsedMilliseconds} ms\n{stopwatch.ElapsedTicks} ticks"); | |
Console.WriteLine("---------------------------------------"); | |
} | |
static void ExampleCopy(ExampleStruct exampleStruct) | |
{ | |
var sum = exampleStruct.Sum(); | |
Console.WriteLine($"Сумма: {sum}"); | |
} | |
static void ExampleRef(in ExampleStruct exampleStruct) | |
{ | |
var sum = exampleStruct.Sum(); | |
Console.WriteLine($"Сумма: {sum}"); | |
} | |
} | |
struct ExampleStruct | |
{ | |
private int[] _numbers; | |
private int _maxSize = 10; | |
public ExampleStruct() | |
{ | |
_numbers = new int[_maxSize]; | |
Fill(); | |
} | |
public long Sum() | |
{ | |
long sum = 0; | |
for (int i = 0; i < _numbers.Length; i++) | |
{ | |
sum += _numbers[i]; | |
} | |
return sum; | |
} | |
public void PrintSize() | |
{ | |
int size = sizeof(int) * _maxSize; | |
Console.WriteLine($"Размер массива int[{_maxSize}] = {size} bytes\n"); | |
} | |
private void Fill() | |
{ | |
for (int i = 0; i < _numbers.Length; i++) | |
{ | |
_numbers[i] = i; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment