简体   繁体   中英

What data structure should I use for integer pairs?

I am trying to optimize my code to speed up calculations and reduce memory consumption. I need to store data for the year and the cost. Currently I use fixed arrays to hold values.

For example, I would have an integer array:

integer[0] = 0,  
integer[1] = 200,  
integer[2] = 0,  
integer[3] = 0,  
integer[4] = 200,  
integer[5] = 0,  
...   
integer[99] = 0

Where integer[0] = 0 means at year 2015 is cost is $0, integer[1] = 200 means at 2016 the cost is $200 and so on. Since I have millions of these arrays held in memory and used for calculations, I want to minimize the memory and performance impact.

To clarify, the way I use the data is for charting purposes. Once I assign costs to the years, I sum up the arrays based on the object series they are part of. Then I display them in a stacked bar chart.

Is there a better way of storing my data? I'm considering key-value list so I only store the non-zero costs and year but I don't know if that would help much.

Use a Dictionary<int, int> :

var costs = new Dictionary<int, int> {
    { 2014, 150 },
    { 2016, 200 },
};

It may not use up less memory necessarily, but you can avoid storing empty entries, and the meaning of the data is a bit more obvious.

If (1) all you are doing is summing, and (2) don't require lookup access to any given value but are simply iterating through them, and (3) your values are truly sparse,

then something like

integer[0] = 200,  
integer[1] = 200,  
...   

combined with

year[0] = 2016,
year[1] = 2019,
...

will get you a minimum memory footprint, without loss of efficiency. Dictionaries (hashes) cost memory; an array is most economical for memory footprint, and even more so if you have a default value (0) that can be assumed for omitted years. But this only works if you don't need to do lookup, since with this structure that's an O(n) exercise.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM