math: Avoid unneeded extra allocations for fixed-size data structures.
authorBen Pfaff <blp@cs.stanford.edu>
Sat, 29 Jan 2022 18:52:49 +0000 (10:52 -0800)
committerBen Pfaff <blp@cs.stanford.edu>
Wed, 1 Jun 2022 17:32:17 +0000 (10:32 -0700)
This seems generally a bit cleaner to me.

src/math/percentiles.c
src/math/percentiles.h
src/math/trimmed-mean.c
src/math/trimmed-mean.h
src/math/tukey-hinges.c
src/math/tukey-hinges.h

index b43fed461612d7a6f0e63ab8ddbc0fad7f549422..1b4ff136328ecdbe0ba9fb2cd1bff521519d5803 100644 (file)
@@ -139,8 +139,6 @@ static void
 destroy (struct statistic *stat)
 {
   struct percentile *ptl = UP_CAST (stat, struct percentile, parent.parent);
-  struct order_stats *os = &ptl->parent;
-  free (os->k);
   free (ptl);
 }
 
@@ -159,7 +157,7 @@ percentile_create (double p, double W)
   ptl->w = W;
 
   os->n_k = 2;
-  os->k = xcalloc (2, sizeof (*os->k));
+  os->k = ptl->k;
   os->k[0].tc = W * p;
   os->k[1].tc = (W + 1.0) * p;
 
index 7af157b230e07adf4c68f01d401eb2ec7e133e45..86fd641addd46d5e6c3c955e547421a04649cf65 100644 (file)
@@ -44,6 +44,8 @@ struct percentile
 
   double g2;
   double g2_star;
+
+  struct k k[2];
 };
 
 /* Create the Pth percentile.
index b643651a26aa4240e0340768b32af1c3ed37a320..4840fd2d66e0375a6114e3585fc5795b9acf60d7 100644 (file)
@@ -44,8 +44,6 @@ static void
 destroy (struct statistic *s)
 {
   struct trimmed_mean *tm = UP_CAST (s, struct trimmed_mean, parent.parent);
-  struct order_stats *os = &tm->parent;
-  free (os->k);
   free (tm);
 }
 
@@ -57,7 +55,7 @@ trimmed_mean_create (double W, double tail)
   struct statistic *stat = &os->parent;
 
   os->n_k = 2;
-  os->k = xcalloc (2, sizeof (*os->k));
+  os->k = tm->k;
 
   assert (tail >= 0);
   assert (tail <= 1);
index baa84bc24e23792e9d53305c0f027426e2622367..8803a127bc203b8e1acc0e2978a0bf446f371405 100644 (file)
@@ -32,6 +32,8 @@ struct trimmed_mean
 
   double w;
   double tail;
+
+  struct k k[2];
 };
 
 struct trimmed_mean * trimmed_mean_create (double W, double c_min);
index aaf4881afa954e79e2a9b731188572072df1b558..b59b878ba64991c2bea385553e24c8e058ab8c2e 100644 (file)
@@ -64,10 +64,7 @@ static void
 destroy (struct statistic *s)
 {
   struct tukey_hinges *th = UP_CAST (s, struct tukey_hinges, parent.parent);
-  struct order_stats *os = &th->parent;
-
-  free (os->k);
-  free (s);
+  free (th);
 };
 
 struct tukey_hinges *
@@ -81,7 +78,7 @@ tukey_hinges_create (double W, double c_min)
   assert (c_min >= 0);
 
   os->n_k = 3;
-  os->k = xcalloc (3, sizeof (*os->k));
+  os->k = th->k;
 
   if (c_min >= 1.0)
     {
index 4b509da1d4321a8396510fd4c08b40d801214ffe..5a6e07950965a100053b58e3052e8a06d1da0aa8 100644 (file)
@@ -25,6 +25,7 @@
 struct tukey_hinges
 {
   struct order_stats parent;
+  struct k k[3];
 };
 
 struct tukey_hinges * tukey_hinges_create (double W, double c_min);