This application on-line here has interesting performance characteristics:
Sorting the rectangles to be drawn so it keeps having to change colour is faster than sorting the rectangles by their colour and drawing all of each colour at once...
(Timings are printed to Javascript console. Javascript profiling and understanding what is happening between the emitting of draw ops and the actual rendering of frames is, well, guesswork and disappointment. But the result is still surprising (to me).)
I'm very interested in the fps logged to the javascript console when run in your browser, and how it differs when sorted by colour vs sorted by z
Now naturally I assume GPU batches are expensive and in my normal apps I get that impression, but I cannot distill a simple test case to show this; quite the opposite, in fact!
Deep in my code, it places all the vertex data interleaved into a single big VBO array. It then calls glDrawArrays
as often as needed. So drawing a rectangle (6 vertices, each 4 floats) in three colours can be:
- Red*1,Blue*1,Red*1 = 3
glDrawArrays
calls - Red*2,Blue*1 = 2
glDrawArrays
calls, but is slower
I am not sorting, creating, uploading the vertices each frame. I compute the buffers to draw once. Each frame, I simply call glDrawArrays
as often as needed.
Because I've built this vertex attribute VBO once, and keep reusing it, I have a tight little draw-loop for rendering each frame. So the Javascript code is doing more work when I have lots of little calls, and less work when I'm emitting concatenated rectangles.
So why is it faster to call glDrawArrays
multiple times with small sub-sequences of the array, instead of calling it only a few times and telling it draw long sequences from the array?
Related: there's +500 pts up for grabs over on StackOverflow for the best general discussion about optimising the drawing of a 2D scene.