Reputation: 15885
I'm writing some memory-sensitive code where for various reasons I must box some value types. Moreover, after some warm-up, I need net new heap allocations to be 0. After I've boxed N
values, my algorithm needs no more storage, but these values must be updated frequently. I would like to be able to reuse the boxes already created on the heap.
The following code suggests that boxes aren't reused (I can imagine why not). Is there different technique where I can reuse each box?
using System;
public class Program
{
public static void Main()
{
object x = 42;
object y = x;
x = 43;
bool isSameBox = Object.ReferenceEquals(x, y);
Console.WriteLine("Same box? {0}.", isSameBox);
}
}
// Output: "Same box? False."
Upvotes: 3
Views: 223
Reputation: 15885
My solution was to introduce an explicit reference type to be the reusable box.
public class ReusableBox<T> where T : struct
{
public T Value { get; set; }
public ReusableBox()
{
}
public ReusableBox(T value)
{
this.Value = value;
}
public static implicit operator T(ReusableBox<T> box)
{
return box.Value;
}
public static implicit operator ReusableBox<T>(T value)
{
return new ReusableBox<T>(value);
}
}
Upvotes: 2