2

我正在制作一个 SDL 程序,有时我需要获取矩形的宽度。当我做这样的事情时:

        int VideoWidth = Video.Screen.Width; //Expensive operation
        int VideoHeight = Video.Screen.Height;

        int ChunksRendered = 0;
        foreach (Chunk c in Chunks)
        {
            if (c.X + 256 + DeferredX > 0 && c.X + DeferredX < VideoWidth)
            {
                if (c.Y + 256 + DeferredY > 0 && c.Y + DeferredY < VideoHeight)
                {
                    BlitSurface.Blit(c.Render(ref Textures, ref BlitSurface), new Point(c.X + DeferredX, c.Y + DeferredY));
                    ChunksRendered++;
                }
            }
        }

我的机器上大约有 550 FPS,但是当我这样做时:

        int ChunksRendered = 0;
        foreach (Chunk c in Chunks)
        {
            if (c.X + 256 + DeferredX > 0 && c.X + DeferredX < Video.Screen.Width)
            {
                if (c.Y + 256 + DeferredY > 0 && c.Y + DeferredY < Video.Screen.Height)
                {
                    BlitSurface.Blit(c.Render(ref Textures, ref BlitSurface), new Point(c.X + DeferredX, c.Y + DeferredY));
                    ChunksRendered++;
                }
            }
        }

我只能得到大约 200 FPS。在进行分析时,很明显这会导致速度变慢,但是为什么要让这个变量如此昂贵呢?

4

1 回答 1

5

可能是Video.Screen属性访问器导致了这种减速。如果您使用SdlDotNet.dll,这里是该属性的代码:

public static Surface Screen
{
    get
    {
        return Surface.FromScreenPtr(Tao.Sdl.Sdl.SDL_GetVideoSurface());
    }
}

Surface这意味着每次访问属性时都会调用 1 个外部 dll 函数并创建 1 个对象Video.Screen

访问WidthHeight属性Surface也很昂贵,因为它包括调用以下代码:

internal Tao.Sdl.Sdl.SDL_Surface SurfaceStruct
{
    get
    {
        if (this.disposed)
        {
            throw new ObjectDisposedException(this.ToString());
        }
        GC.KeepAlive(this);
        return (Tao.Sdl.Sdl.SDL_Surface) Marshal.PtrToStructure(base.Handle, typeof(Tao.Sdl.Sdl.SDL_Surface));
    }
}
于 2013-05-26T01:32:17.183 回答