简体   繁体   English

整数对应使用什么数据结构?

[英]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. 其中integer [0] = 0表示在2015年的成本为$ 0,integer [1] = 200表示在2016年的成本为$ 200,依此类推。 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> : 使用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, 如果(1)您所做的只是求和,(2)不需要对任何给定值的查找访问权,而只是对其进行迭代,并且(3)您的值确实是稀疏的,

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. 对于内存占用空间而言,阵列是最经济的,如果您可以将默认值(0)假定为省略年份,则数组更是如此。 But this only works if you don't need to do lookup, since with this structure that's an O(n) exercise. 但这仅在不需要查找时才有效,因为使用此结构是O(n)练习。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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