Large 1px Lines in D3

JavaScript performance comparison

Test case created by Thomas Suckow

Info

Compare drawing a single line in d3 vs chunking it into pieces that share a point.

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://d3js.org/d3.v2.js"></script>
<style>
.line {
    fill: none;
    stroke: black;
    stroke-width: 1px;
}
</style>

<div id="graph" style="height:100px;"></div>
<script>
Benchmark.prototype.setup = function() {
    var points = [];
        for( var i = 0; i < 16000; ++i )
        {
            points.push(Math.random());
        }
   
    var element = $("#graph");
    var width = element.width(),
        height = element.height();
   
    // set up initial svg object
    var vis = d3.select(element[0])
       .append("svg")
       .attr("width", width)
       .attr("height", height);
   
    var x = d3.scale.linear().range([0,width]);
            var y = d3.scale.linear().range([height, 0]);
            x.domain([0,points.length]);
            y.domain(d3.extent(points));
   
    function drawLine( data, offset )
    {
        var line = d3.svg.line()
               .x(function(d) { return x(d[0]); })
               .y(function(d) { return y(d[1]); });
   
            var d = data.map( function(v,i) { return [i+offset,v]; } );
   
            vis.append("path")
               .datum(d)
               .attr("class", "line")
               .attr("d", line);
    }
   
    function chunk(array,x)
        {
            var arrays=[];
            while(array.length>0)arrays.push((array.length<x)?array.splice(0,x):array.splice(0,x,array[x-1]));
            return arrays;
        }
   
    function drawChunked(num) {
    chunk(points,num).forEach(function(data,index){drawLine(data,(num-1)*index);});
    }
   
    function finish()
    {
    setTimeout(function() {
      deferred.resolve();
    }, 1);
    }
};

Benchmark.prototype.teardown = function() {
    element[0].innerHTML = ''
};
</script>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Single Line
// async test
drawLine(points,0);
finish();
pending…
10 Points
// async test
drawChunked(10);
finish();
pending…
100 Points
// async test
drawChunked(100);
finish();
pending…
200 Points
// async test
drawChunked(200);
finish();
pending…
400 Points
// async test
drawChunked(400);
finish();
pending…
1000 Points
// async test
drawChunked(1000);
finish();
pending…
2000 Points
// async test
drawChunked(2000);
finish();
pending…
4000 Points
// async test
drawChunked(4000);
finish();
pending…

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

Compare results of other browsers

0 comments

Add a comment