How to initialize a List to a given size (as opposed to capacity)?

前端 未结 15 2199
礼貌的吻别
礼貌的吻别 2020-11-28 06:41

.NET offers a generic list container whose performance is almost identical (see Performance of Arrays vs. Lists question). However they are quite different in initialization

15条回答
  •  佛祖请我去吃肉
    2020-11-28 07:02

    Why are you using a List if you want to initialize it with a fixed value ? I can understand that -for the sake of performance- you want to give it an initial capacity, but isn't one of the advantages of a list over a regular array that it can grow when needed ?

    When you do this:

    List = new List(100);
    

    You create a list whose capacity is 100 integers. This means that your List won't need to 'grow' until you add the 101th item. The underlying array of the list will be initialized with a length of 100.

提交回复
热议问题