Best Way To Clear WriteableBitmap?

Nov 11, 2009

If you're doing a lot of custom drawing using WriteableBitmap (e.g. full screen game), it will be extremely important to be able to clear the WriteableBitmap or "screen" quickly.

Lets assume you want to clear the screen to specific color.

What is the best way to do it?

Here is a short comparison of few methods to clear a 512x512 bitmap:

  • Clear with for loop: 1000 FPS
  • Clear with Array.Copy: 4100 FPS
  • Clear with Array.Clear: 11000 FPS

1. Clear with for() loop. This method is the most straight-forward, and also the slowest:

public static void ClearForLoop(int[] pixels, int len, int color)
    for (int i = 0; i < len; i++)
        pixels[i] = color;

2. Clear by using Array.Copy. This method is not only fast, but it also allows to "clear" to an image (not just color), which is great if you have a pre-defined background or something like that.

public static void ClearArrayCopy(int[] pixels, int[] clearTo, int len)
    Array.Copy(clearTo, 0, pixels, 0, len);

This method assumes that you have already pre-initialized the "clear" bitmap (just do it once! :) with the color/image:

// note: do this ONCE!, NOT on every frame! obvious, but worth mentioning just in case

int[] clearScreen = new int[pixels.Length];

for (int i = 0; i < pixels.Length; i++)
    clearScreen[i] = color;

3. Clear with Array.Clear: the fastest way, but unfortunately allows you to clear to 0 only (meaning transparent image).

Array.Clear(pixels, 0, pixels.Length);

Depending on the application you'd either choose Array.CopyTo(), since it's the most versatile or Array.Clear(). You may also choose Array.CopyTo() over Array.Clear() because Array.CopyTo() is easily multithreaded, and can take advantage of multiple cores, while Array.Clear() currently runs on a single thread/core.

Note that all measurements assume single-core used. If you have multiple-core system you can improve the speed quite a bit by running those multithreaded.

blog comments powered by Disqus | Terms | Log in


About the author

Happy & enjoying life. Software enthusiast.
The opinions I express here and on are mine and not my employeer's (Microsoft).
This is the official blog of You can find Silverlight samples, coding stuff, and hopefully other interesting things here.