从对象中传递对象会产生垃圾吗?

问题描述 投票:1回答:1

我想完全优化一个类,以便它在生命周期中不会产生垃圾(不包括实例化和破坏)但我也希望从方法中返回一个对象 - 这可能吗?

以下是这种情况的一个例子:

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...
}

我想,询问是否将对象分配给已存在的引用会产生垃圾会更准确。

- [编辑] -

只是上下文,如果你想知道:这个方法将用于从精灵表中获取精灵的源矩形。由于精灵表有动画条,这个调用将每秒无数次,所以任何孤立的对象都会很快加起来。

c# garbage-collection variable-assignment
1个回答
1
投票

如果要分配的对象是值类型,则将彻底替换该值。否则,如果它是一个引用类型,它将孤立前一个对象并将其标记为“无法访问”,以后可以通过GarbageCollector删除/收集它。

在我们的场景中,我相信,它是一个值类型(struct),因此它将被替换而不会产生垃圾。

此外,GarbageCollector没有固定的间隔来运行和收集,它根据以下链接中提到的条件运行:

https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals#conditions_for_a_garbage_collection

C# Garbage collection?

您还会发现这些有用:

C# The 'new' keyword on existing objects

https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/

© www.soinside.com 2019 - 2024. All rights reserved.