Я хочу полностью оптимизировать класс, чтобы он никогда не создавал мусор в течение своего жизненного цикла (исключая создание экземпляров и уничтожение), но я также хочу вернуть объект из метода - это возможно?
ЗдесьПример такой ситуации:
public class Example
{
/// <summary>
/// Width of each column - gets set by the constructor.
/// </summary>
private int columnWidth = 0;
/// <summary>
/// Height of each row - gets set by the constructor.
/// </summary>
private int rowHeight = 0;
/// <summary>
/// Internal working rectangle to avoid garbage collection.
/// Created only once for each instance of encapsulating class.
/// </summary>
private Rectangle rectangle = new Rectangle(0, 0, 0, 0);
/// <summary>
/// Initializes a new instance of the <see ref="Example"> class.
/// </summary>
/// <param name="columnWidth">Column width.</param>
/// <param name="rowHeight">Row height.</param>
public Example(int columnWidth, int rowHeight)
{
this.columnWidth = columnWidth;
this.rowHeight = rowHeight;
}
/// <summary>
/// Constructs and returns a rectangle for this class.
/// </summary>
/// <param name="column">Column for the rectangle to represent.</param>
/// <param name="row">Row for the rectangle to represent.</param>
/// <returns>Constructed rectangle for column and row.</returns>
public Rectangle GetRectangle(int column, int row)
{
this.rectangle.Width = this.columnWidth;
this.rectangle.Height = this.rowHeight;
this.rectangle.X = column * this.columnWidth;
this.rectangle.Y = row * this.rowHeight;
return this.rectangle;
}
}
public class OtherClass
{
// some other unimportant stuff going on...
/// <summary>
/// Internal rectangle.
/// </summary>
private Rectangle rec = new Rectangle(0, 0, 0, 0);
/// <summary>
/// Does some stuff.
/// </summary>
private void DoStuff()
{
var exampleClass = new Example(20, 20);
// --- THIS IS THE PART I AM CONCERNED ABOUT ---
// Does this assignment over-write the previous assignment (no garbage)?
// - or -
// Does this produce a new assignment and orphan the old one (creates garbage)?
this.rec = exampleClass.GetRectangle(1, 3);
}
// some more other unimportant stuff going on...
}
Полагаю, было бы точнее спросить, производит ли присвоение объекта уже существующей ссылке мусор.
- [Редактировать] --
Просто из контекста, если вам интересно: этот метод будет использоваться для получения исходного прямоугольника для спрайта из листа спрайта.Поскольку на листах спрайтов есть полосы анимации, этот вызов будет выполняться бесчисленное количество раз в секунду, поэтому любые осиротевшие объекты будут складываться довольно быстро.