What is the best way to set background for some view? For example 2 variants of backround:
- background with gradient, rounded corners and border
- background with just one color and rounded corners
So which of variants would be better, nine-patch or drawable xml resource?
My guess is,
NinePatch
would be slightly faster in most cases. Here's what I found.GradientDrawable
(the one used for rects in xml) uses this code to call through toCanvas
which in turn uses native call leading toSkCanvas
,SkDraw
and eventuallySkScan
andSkBlitter
.On the other hand,
NinePatch
's draw() has almost zero Java code before the native call toNinePatch.cpp
which shortly callsNinePatchImpl.cpp
--NinePatch_draw()
--- and that's where the magic is. The code there iterates over the marked regions and after a number of subsequent calls draws stuff using roughly the same logic inSkDraw
(onlydrawRect()
instead ofdrawPath()
) but in the end it's the sameSkScan
andSkBlitter
that do the work.All that code is pretty hard to wrap my head around instantly, but what did catch my eye is that
GradientDrawable
makes two calls to the whole native stack if it has both background and stroke (look here), while in any scenario aNinePatch
only makes one.So, without actually measuring times for both approaches I get a feeling in most cases
NinePatch
wins the race: if we [awfully] roughly assume that native call stacks fordrawRect()
anddrawPath()
use pretty much the same logic and [another awful simplification] the parameter sets that get passed around there and are created byNinePatch
andGradientDrawable
don't affect complexity of the methods that much, thenNinePatch
turns out to be roughly 2 times faster thanGradientDrawable
with filling and outline. Well, provided you use a regular, 9-section 9-Patch (i.e. don't shred you 9-Patch by an awful lot of markers, making the iteration over the pieces overly effort-expensive).Anyone who'll stumble upon this and knows more on the subject (and/or better at estimating complexity of native code), please, correct me if I'm wrong.
PS yeah, I know this is not much of a straight answer