C
C#2mo ago
ikalou.

List, Collection Initializer and Capacity

Hi! Does creating a new List with new List<T> { new T() } (or any number of elements > 0) starts with the proper capacity in order to avoid resizes or does it start at 0 and then grows to add the elements and I should be using new List<T>(1) { new T() } (for instance) instead? Thanks for helping me figure this out!
43 Replies
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
ikalou.
ikalou.2mo ago
I think the docs say new List<T> starts at 0 (instead of 4)?
MODiX
MODiX2mo ago
TeBeCo
REPL Result: Success
(new List<int>()).Capacity
(new List<int>()).Capacity
Result: int
0
0
Compile: 204.168ms | Execution: 17.922ms | React with ❌ to remove this embed.
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
MODiX
MODiX2mo ago
TeBeCo
REPL Result: Success
(new List<int>() {1}).Capacity
(new List<int>() {1}).Capacity
Result: int
4
4
Compile: 268.383ms | Execution: 25.126ms | React with ❌ to remove this embed.
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
MODiX
MODiX2mo ago
TeBeCo
REPL Result: Success
(new List<int>(3) {1}).Capacity
(new List<int>(3) {1}).Capacity
Result: int
3
3
Compile: 234.006ms | Execution: 27.054ms | React with ❌ to remove this embed.
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
SleepWellPupper
SleepWellPupper2mo ago
var l = new List<T>()
{
new T(),
new T(),
new T()
}
var l = new List<T>()
{
new T(),
new T(),
new T()
}
gets turned into
var l = new List<T>();
l.Add(new T());
l.Add(new T());
l.Add(new T());
var l = new List<T>();
l.Add(new T());
l.Add(new T());
l.Add(new T());
To answer your question
MODiX
MODiX2mo ago
TeBeCo
REPL Result: Success
var l = new List<int>();
l.Add(1);
l.Capacity
var l = new List<int>();
l.Add(1);
l.Capacity
Result: int
4
4
Compile: 338.572ms | Execution: 21.330ms | React with ❌ to remove this embed.
SleepWellPupper
SleepWellPupper2mo ago
So it will grow accordingly
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
ikalou.
ikalou.2mo ago
My question is‚ when using a collection initializer with n elements‚ is new List<T>() {...} be as efficient as new List<T>(n) {...}. It would seem logical but I can't find the information nor do I know how to test it.
Unknown User
Unknown User2mo ago
Message Not Public
Sign In & Join Server To View
MODiX
MODiX2mo ago
TeBeCo
REPL Result: Success
(new List<int>() {1}).Capacity
(new List<int>() {1}).Capacity
Result: int
4
4
Compile: 268.383ms | Execution: 25.126ms | React with ❌ to remove this embed.
Want results from more Discord servers?
Add your server