SVG path updating

Benchmark created by Smal Sergey on


Description

Updating path line in fixed area. (simulation of line chart)

Setup

var ns = "http://www.w3.org/2000/svg";
    var svg = document.createElementNS(ns, "svg");
    var path = document.createElementNS(ns, "path");
    path.points = [];
    svg.appendChild(path);
    document.body.appendChild(svg);
    
    var gap = 2;
    var lineWidth = 25;
    var step = 2;
    var lineHeight = 10;
    
    var values = [];
    for (var i = 0; i < 10000; i++) {
      values.push(Math.random() * lineHeight);
    }

Test runner

Ready to run.

Testing in
TestOps/sec
Update path through SVG API
function updateLine( /**SVGPathElement*/ path, value) {
  var newPoint = {
    x: (gap + lineWidth),
    y: value
  };
  var pathSegList = path.pathSegList;
  if (!pathSegList.numberOfItems) {
    var curX = gap + lineWidth;
    pathSegList.appendItem(path.createSVGPathSegMovetoAbs(curX, lineHeight));
    var numberSegments = Math.round(lineWidth / step);

    for (var i = 0; i < numberSegments; i++) {
      curX -= step;
      pathSegList.appendItem(path.createSVGPathSegLinetoAbs(curX, lineHeight));
    }
  } else {
    for (var i = pathSegList.numberOfItems - 1; i > 0; i--) {
      var prevItem = pathSegList.getItem(i - 1);
      pathSegList.getItem(i).y = prevItem.y;
    }
    pathSegList.getItem(0).y = newPoint.y;
  }
  path.style.fillOpacity = 0;
  path.style.stroke = "#cccccc";
}

for (var i = 0; i < values.length; i++) {
  updateLine(path, values[i]);
}
ready
Update path through forming 'd' attribute
function updateLine2( /**SVGPathElement*/ path, value) {
  var newPoint = {
    x: (gap + lineWidth),
    y: value
  };
  var d = "M" + newPoint.x + "," + newPoint.y;

  if (path.points.length > 0 && path.points[0].x < step + gap) {
    path.points.splice(0, 1); //remove first point
  }

  path.points.push(newPoint);
  var length = path.points.length;

  for (var i = 0; i < length - 1; i++) {
    path.points[i].x = path.points[i].x - step;
  }

  for (var i = length - 2; i >= 0; i--) { //all but the last
    var point = path.points[i];
    d += " L" + point.x + "," + point.y
  }

  path.setAttribute("stroke", "#cccccc");
  path.setAttribute("d", d);
}

for (var i = 0; i < values.length; i++) {
  updateLine2(path, values[i]);
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Smal Sergey on
  • Revision 2: published by muffin on