Is it worth to resize a List in C#? -
i intending use list in c# program. now, everytime call function maketemplate
contents size of list change. thinking of resizing list (haven't thought of how yet, heard addrange might ok this) thought, why not create another list, abandon previous 1 , let gc deal that. along these lines
class aclass { private list<float> template; public ivoid maketemplate(size) { //here abandon previous template hold in memory , //get new list template= new list<float>(size); //..... } }
i thinking better way, opinion on this? (i imagine in c++ have check if null , delete memory before doing this)
the list resize buffer automatically, there's no point in creating new list , throwing away old one. can set list capacity if know final size in advance--this save memory making buffer big need. save cpu time if increase in size dramatic involves multiple resize/copy operations--your code need 1 operation.
the c# list
class works same c++ vector
, if you're more familiar c++. in each, buffer doubled each time increases.
addrange
automatically increases list size right number, instead of potentially increasing more once during addition of elements if add one-by-one.
so in short, don't worry it, use addrange
if it's equally convenient, , set list capacity if know in advance.
if want see c# source, these important classes analyzing performance of containers: enumerable, list.
Comments
Post a Comment