Skip to content

Instantly share code, notes, and snippets.

@smoothdeveloper
Created April 5, 2020 17:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smoothdeveloper/21eb65b82a199eb6df128166853b5c74 to your computer and use it in GitHub Desktop.
Save smoothdeveloper/21eb65b82a199eb6df128166853b5c74 to your computer and use it in GitHub Desktop.
Samples from Matt Ellis "Writing Allocation Free Code in C#" talk
// replicating same techniques as
// https://youtu.be/1ZJ8ROVS5gk?t=1435
[<Struct>]
type Point =
val mutable X : int
val mutable Y : int
new(x, y) = { X = x; Y = y }
type Enemy(location: Point) =
let mutable location = location
member x.GetLocation() = location
member x.GetLocationRef() = &location
let areEqual x y =
if x = y then () else failwithf "not equal"
let ``struct return value is a copy`` () =
let enemy = Enemy(Point(10,10))
let mutable location = enemy.GetLocation()
location.X <- 12
areEqual 12 location.X
areEqual 10 (enemy.GetLocation().X)
let ``ref return value is a copy`` () =
let enemy = Enemy(Point(10,10))
let mutable point = enemy.GetLocationRef()
point.X <- 12
areEqual 12 point.X
areEqual 10 (enemy.GetLocation().X)
let ``ref return to ref not a copy`` () =
let enemy = Enemy(Point(10,10))
let point = &enemy.GetLocationRef()
point.X <- 12
areEqual 12 point.X
areEqual 12 (enemy.GetLocation().X)
let ``method as lhs`` () =
let enemy = Enemy(Point(10,10))
enemy.GetLocationRef() <- Point(42,42)
areEqual 42 (enemy.GetLocation().X)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment