Getting a better performance on repeatedly method on d3

后端 未结 2 430
孤街浪徒
孤街浪徒 2021-01-15 03:44

For example, I need to calculate a Math.sqrt of my data for each attr, how can I calculate only one time the Math.sqrt(d)?

var circle = svgContainer.data(dat         


        
2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-15 04:27

    An underestimated feature of D3 is the concept of local variables which were introduced with version 4. These variables allow you to store information on a node (that is the reason why it is called local) independent of the data which might have been bound to that node. You don't have to bloat your data to store additional information.

    D3 locals allow you to define local state independent of data.

    Probably the major advantage of using local variables over other approaches is the fact that it smoothly fits into the classic D3 approach; there is no need to introduce another loop whereby keeping the code clean.

    Using local variables to just store a pre-calculated value is probably the simplest use case one can imagine. On the other hand, it perfectly illustrates what D3's local variables are all about: Store some complex information, which might require heavy lifting to create, locally on a node, and retrieve it for later use further on in your code.

    Shamelessly copying over and adapting the code from Gerardo's answer the solution can be implemented like this:

    var svg = d3.select("svg");
    
    var data = d3.range(100, 1000, 100);
    
    var roots = d3.local();   // This is the instance where our square roots will be stored
    
    var ellipses = svg.selectAll(null)
      .data(data)
      .enter()
      .append("ellipse")
      .attr("fill", "gainsboro")
      .attr("stroke", "darkslateblue")
      .attr("cx", function(d) {
        return roots.set(this, Math.sqrt(d)) * 3;  // Calculate and store the square root
      })
      .attr("cy", function(d) {
        return roots.get(this) * 3;                // Retrieve the previously stored root
      })
      .attr("rx", function(d) {
        return roots.get(this) + 3;                // Retrieve the previously stored root
      })
      .attr("ry", function(d) {
        return roots.get(this) + 4;                // Retrieve the previously stored root
      });
    
    

提交回复
热议问题