java - What is the best practice for setting the initial capacity of an ArrayList that is not always used? -
i have classes have arraylist fields used. initialize these fields so:
private list<widget> widgets = new arraylist<>(); i understand using overload constructors set initial capacity, i'm wondering if should declare these fields such:
private list<widget> widgets = new arraylist<>(0); the dilemma, if initialize list 0 list always have re-initialize adding 1 item. but, if use default constructor, gives default capacity of 10, may have bunch of items (and there can many) wasting memory unused capacity.
i know of going push asking 'how often' , 'how many items expecting' i'm looking "best practices" approach. things being ~equal, should 1 initialize (0) or () on list used?
it's our department policy always initialize lists, may not leave lists null, besides, side-step question.
premature optimisation root of evil. - d. knuth.
this seems kind of "performance issue" never has effect on performance. 1 thing, how sure these empty lists initialised? suspect modern compilers delay initialisation of objects until know sure there call on them. if pass no arg constructor never used unless added list. on other hand, if use 0 argument constructor, guarantees has resize every 1 uses.
these 3 laws of performance optimisation
- never assume know compiled code doing, or can sport small optimisations better compiler can.
- never optimise without using profiler work out bottleneck is. if think know, refer rule number (1).
- don't bother unless application has performance issue. refer rule (2).
on off chance somehow still believe understand compilers, check out question: why faster process sorted array unsorted array?
Comments
Post a Comment