函数内的常量字符串

发布于 2024-12-07 09:01:33 字数 1169 浏览 1 评论 0原文

来自Mricrosoft XNA Education Catalog 的片段:

    /// <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 次。在绘图内分配消息是否有任何性能开销?这和我将它移动到静态帮助器类一样吗?据我记得,成本表达式是由 C# 编译器计算的。这里const修饰符改变了什么?

A snippet from Mricrosoft XNA Education Catalog:

    /// <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 is called 60 times per second. Is there any performance overhead with assigning message inside the draw? Is it the same as if I move it to static helper class? As far I recall, cost expression is evaluated by C# compiler. What const modifier change here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

深空失忆 2024-12-14 09:01:33

const 仅被评估一次。将其移至静态变量中不会获得任何好处。

A const is evaluated once only. You gain nothing by moving it away into a static variable.

风铃鹿 2024-12-14 09:01:33

不,它全部为您优化。

Nope its all optimized for you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文