函数内部的Const字符串

本文关键字:字符串 Const 内部 函数 | 更新日期: 2023-09-27 18:10:05

来自microsoft XNA教育目录的一个片段:

    /// <summary>
    /// Draws the control, using SpriteBatch and SpriteFont.
    /// </summary>
    protected override void Draw()
    {
        const string message = "Hello, World!'n" +
                               "'n" +
                               "I'm an XNA Framework GraphicsDevice,'n" +
                               "running inside a WinForms application.'n" +
                               "'n" +
                               "This text is drawn using SpriteBatch,'n" +
                               "with a SpriteFont that was loaded'n" +
                               "through the ContentManager.'n" +
                               "'n" +
                               "The pane to my right contains a'n" +
                               "spinning 3D triangle.";
        GraphicsDevice.Clear(Color.CornflowerBlue);
        spriteBatch.Begin();
        spriteBatch.DrawString(font, message, new Vector2(23, 23), Color.White);
        spriteBatch.End();
    }

Draw每秒被调用60次。在draw中分配消息是否有性能开销?如果我把它移动到静态助手类是一样的吗?据我回忆,成本表达式是由c#编译器计算的。这里const修饰符改变了什么?

函数内部的Const字符串

const只计算一次。将它移到一个静态变量中,您将一无所获。

都是为你优化的