]> granicus.if.org Git - graphviz/commitdiff
dijkstra: remove an allocator optimization
authorMatthew Fernandez <matthew.fernandez@gmail.com>
Sun, 19 Dec 2021 19:30:03 +0000 (11:30 -0800)
committerMatthew Fernandez <matthew.fernandez@gmail.com>
Sun, 19 Dec 2021 23:14:36 +0000 (15:14 -0800)
This function was using a static local for the index array under the assumption
that resizing an existing dynamically allocated buffer is cheaper than
allocating a new one. This is generally not true in this use case. Calling
`realloc` here was (incorrectly) telling the allocator the caller needed to
retain the prior content of the array. In other words, this was actually a
_deoptimization_. Undoing this and letting the allocator more accurately
perceive that this is a transient array allocation results in (1) more efficient
behavior and (2) less unnecessarily retained memory.

lib/neatogen/dijkstra.c

index 377b353264e3499ce8b382e8684f23b5d127ff9e..2c5011b071c9b4a9f3156afce4627c325f2b6e71 100644 (file)
@@ -17,7 +17,7 @@
 
 ******************************************/
 
-
+#include <common/memory.h>
 #include <neatogen/bfs.h>
 #include <neatogen/dijkstra.h>
 #include <limits.h>
@@ -140,9 +140,8 @@ void dijkstra(int vertex, vtx_data * graph, int n, DistType * dist)
     heap H;
     int closestVertex, neighbor;
     DistType closestDist, prevClosestDist = MAX_DIST;
-    static int *index;
 
-    index = realloc(index, n * sizeof(int));
+    int *index = gcalloc(n, sizeof(int));
 
     /* initial distances with edge weights: */
     for (i = 0; i < n; i++)
@@ -172,6 +171,7 @@ void dijkstra(int vertex, vtx_data * graph, int n, DistType * dist)
        if (dist[i] == MAX_DIST)        /* 'i' is not connected to 'vertex' */
            dist[i] = prevClosestDist + 10;
     freeHeap(&H);
+    free(index);
 }
 
  /* Dijkstra bounded to nodes in *unweighted* radius */