views:

144

answers:

2

As an optimization, I decided to put an object I frequently need - an SDL surface with a prerendered image of the entire level (called S_AreaBMP) - at global scope.
Now it doesn't have to be created and destroyed in the DrawScreen function every frame. I only need to dispose and change it when a new level or GFX sheet is loaded, which I do via this function:

Public Sub PrepareAreaImage()

    ''#dispose old image before it becomes unreferenced
    If AreaBMPExists
        S_AreaBMP.Dispose()
    End If
    AreaBMPExists = True

    ''#declare an appropriately sized bitmap w/ a GDI Graphics object
    Dim AreaBMP As Bitmap = New Bitmap(Area.W * TLDIM, Area.H * TLDIM)
    Dim AreaGrph As Graphics = Graphics.FromImage(AreaBMP)

    ''#...(omitted: iterate through Area and draw each tile to AreaBMP)

    ''#Store to the SDL surface
    S_AreaBMP = New SdlDotNet.Graphics.Surface(AreaBMP)

    ''#Dispose
    AreaBMP.Dispose()
    AreaGrph.Dispose()
End Sub

(AreaBMPExists and S_AreaBMP are global scope)

Question: Is this fundamentally sound?

It works fine, but I can't help but feel that this sort of thing is discouraged...

+1  A: 

You're basically making a static variable at a global scope. There isn't anything technically incorrect in doing this, but it's usually a better option to wrap this using something like the Singleton pattern. This would make it easier to control access to this, and potentially easier to wrap the resource in a way to provide better thread safety, encapsulation of this logic, etc.

Reed Copsey
I know what you're saying, but I wish the GoF had never written about Singleton. Everyone and their dog thinks it's the solution to their static variable problems.
Esteban Araya
Yeah - I agree, but there are times when a Singleton makes at least some sense. In this case, it could probably be refactored to hold the Bitmap in some form of high-level screen class, but that's beyond the scope of the question. I do think singletons are much nicer than a single static global, though - since you can at least provide some control and thread syncrhonization.
Reed Copsey
A: 

Thread safety would be my biggest concern. Particularly, what happens if PrepareAreaImage is called when it is already executing, or S_AreaBMP is accessed sometime during PrepareAreaImage()'s execution.

richardtallent