Does reusing symbols improve SVG performance?

前端 未结 3 854
挽巷
挽巷 2020-12-05 18:11

Assuming a relatively modern, SVG-supporting desktop browser and an SVG consisting of hundreds of similar, simple nodes:

  1. The document could be set up as many i
相关标签:
3条回答
  • 2020-12-05 18:55

    I would advise you to not nest <use> elements deeply. That is known to cause slowdowns in most browsers, see here and here.

    In the general case though it should be fast, at least as long as the template itself isn't changed much (since if you do then each of the instances need to be updated too, and each of them can differ from the rest due to CSS inheritance).

    Between <svg> and <symbol> there isn't that big of a difference on a functional level, they both allow you to define a coordinate system (via the 'viewBox' attribute). A <g> element doesn't let you do that. Note that <symbol> elements are invisible unless referenced by a <use>, whereas <svg> and <g> are both visible per default. However, in most cases it's advisable to make the template be a child of a <defs> element.

    0 讨论(0)
  • 2020-12-05 19:13

    If you change the contents of a g or svg element then a UI can look at the area the old contents were drawn in and where the update will be drawn to and simply redraw those two areas, even redraw only once if they are the same e.g. changing the colour of a shape.

    If you update the contents of a symbol then all the instances must be redrawn. It's harder to do that by calculating for each instance where the old and new parts to redraw are as the areas may be affected by transforms and simpler to just redraw all parts of all instances. Some browsers may do the former and some the latter.

    In either case, a UI must at a minimum track the changes in the symbol and propagate those changes to all the instances. That's more than likely to have some overhead.

    Of course, if you're just moving individual symbol instances and the contents are static then no tracking is required and performance is likely to be similar.

    0 讨论(0)
  • 2020-12-05 19:14

    Rohit Kalkur compared rendering speed of the creation of 5000 SVG symbols using use against directly creating the SVG symbol's shapes, see here. It turns out that rendering SVG shapes using use was almost 50% slower. He reasons that:

    The use element takes nodes from within the SVG document, and duplicates them in a non-exposed DOM

    Given this, I assume that using SVG symbols is at best as performant as manually creating the symbolss shape.

    0 讨论(0)
提交回复
热议问题