mercredi 5 avril 2017

C++ Design struct with content preferences specified at creation time

I would like to create a data structure to capture time series of production, sales, and inventory data. However, for all cases, we don't need to track all the data. The exact data to track (for example sales and inventory but not production) is specified at the time the series is constructed/initiated.

One approach could be the following.

struct ProductionDataEntry { ... };
struct SalesDataEntry { ... };
struct InventoryDataEntry { ... };
// Each of the above struct could be arbitrarily large

struct DataEntryV1 {
  ProductionDataEntry pde_;
  SalesDataEntry      sde_;
  InventoryDataEntry  ide_;
};

typedef std::chrono::system_clock::time_point TimePoint;

struct TimeSeriesEntry {
  TimePoint timepoint_;
  DataEntry entry_;
};

std::deque<TimeSeriesEntry> time_series;

The drawback of the above approach is the following. In the use case, where sales and inventory data is necessary, but not production, the data structure would still consume space for ProductionDataEntry.

I am looking for an approach where I can avoid such space wastage.

Two options come to mind:

  1. Create separate time series for each kind of data and populate only those time series which are necessary. However, this copies TimePoint data multiple times and spoils the locality of data by spreading the collected data over multiple data structures.

  2. Organize DataEntry as pointers to individual data entries, something like

    struct DataEntryV2 { ProductionDataEntry * pde_{nullptr}; SalesDataEntry * sde_{nullptr}; InventoryDataEntry * ide_{nullptr}; };

    and construct only those data entry objects that are necessary. However, this fragments the memory and introduces additional overhead of allocation and deallocation which I would like to avoid if possible.

  3. Organize DataEntry with std::optional, something like

    struct DataEntryV3 { std::optional<ProductionDataEntry> pde_; std::optional<SalesDataEntry> sde_; std::optional<InventoryDataEntry> ide_; };

    I think this requires one extra word per entry type. And it would still consume the space of unnecessary data.

I would like to be aware, are there any other options in the design space?

(Note: DataEntry may need to be extended to include new kind of data, e.g. PreOrderData.)

Aucun commentaire:

Enregistrer un commentaire