Skip to content

Instantly share code, notes, and snippets.

@Stovoy
Created January 14, 2023 02:25
Show Gist options
  • Save Stovoy/04229a08b1caf699ecec69597426344f to your computer and use it in GitHub Desktop.
Save Stovoy/04229a08b1caf699ecec69597426344f to your computer and use it in GitHub Desktop.
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using CommunityToolkit.HighPerformance;
public struct Position {
public float x;
public float y;
};
public class TestStructModification {
public delegate void ActionRef<T>(ref T item);
public List<Position> positions;
[GlobalSetup]
public void Setup() {
positions = new List<Position>();
for (var i = 0; i < 100_000; i++) {
positions.Add(new Position { x = i, y = i });
}
}
[Benchmark]
public void NewWithIncrement() {
Entrypoint(NewWithIncrement);
}
[Benchmark]
public void NewWithAddition() {
Entrypoint(NewWithAddition);
}
[Benchmark]
public void UpdateInPlace() {
Entrypoint(UpdateInPlace);
}
public void Entrypoint(ActionRef<Position> action) {
var positionsSpan = positions.AsSpan();
for (var i = 0; i < positions.Count; i++) {
action(ref positionsSpan[i]);
}
}
public void NewWithIncrement(ref Position position) {
position = new Position {
x = position.x++,
y = position.y++
};
}
public void NewWithAddition(ref Position position) {
position = new Position {
x = position.x + 1,
y = position.y + 1,
};
}
public void UpdateInPlace(ref Position position) {
position.x += 1;
position.y += 1;
}
}
public class Program {
public static void Main(string[] args) {
BenchmarkRunner.Run<TestStructModification>();
}
}
@Stovoy
Copy link
Author

Stovoy commented Jan 14, 2023

Benchmark written for genaray/Arch#49

Very surprising results:

|           Method |     Mean |   Error |  StdDev |   Median |
|----------------- |---------:|--------:|--------:|---------:|
| NewWithIncrement | 199.9 us | 3.34 us | 8.31 us | 197.0 us |
|  NewWithAddition | 194.7 us | 2.82 us | 2.35 us | 194.2 us |
|    UpdateInPlace | 193.0 us | 1.09 us | 0.85 us | 193.1 us |

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment