内存分配(如果列表已添加到列表中) [英] Memory Allocation if a list added to list

查看:54
本文介绍了内存分配(如果列表已添加到列表中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hi Folks,



下面的代码片段是在列表中添加一个列表。





列出

Hi Folks,

Below code snippet is adding a list to anothe list.


List

<string> str1 = new List<string> { "A",   "A", "B", "C", "D", "A", "B", "C", "D", };
            List<string> str2 = new List<string> { "A", "A", "B", "C"};

            str1.AddRange(str2);



我很想知道在这种情况下如何进行内存分配。



1)str1将包含11个元素,第11个元素将指向str2



Str1将包含15个元素。


I am curios to know how the memory allocation will happen in this case.

1) Will str1 contains 11 element and 11th element will be pointing to str2
Or
Str1 will contain 15 element.

推荐答案

不,str1将包含13个元素:

No, str1 will contain 13 elements:
A
A
B
C
D
A
B
C
D
A
A
B
C

之前有9个,你添加了4:9 + 4 == 13

There were 9 before, and you added 4: 9 + 4 == 13


AddRange方法复制在另一个可枚举项中找到的所有项目。名为str2的原始列表可以更改甚至收集,并且在调用AddRange后不会影响str1的内容。



实际上,AddRange非常好类似于:

The AddRange method copies all the items found in another enumerable. The original list named str2 can be changed and even be collected and it will not affect the contents of str1 after the call to AddRange.

In fact, the AddRange is very similar to:
foreach(var value in str2)
  str1.Add(value);





但即使它非常相似,它在很多情况下实际上更快,因为它可以做到单个验证/内部数组调整大小,以便添加每个调用时将添加的所有项目。



But even if it is very similar, it is actually faster in many situations as it can do a single validation/inner array resize for all the items that will be added while the Add will do those validations per call.


这篇关于内存分配(如果列表已添加到列表中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆