Re: Array.Clear vs List<>.Clear
- From: Doug Semler <dougsemler@xxxxxxxxx>
- Date: Thu, 04 Oct 2007 18:08:27 -0000
On Oct 4, 1:59 pm, Peter Duniho <NpOeStPe...@xxxxxxxxxxxxxxxx> wrote:
Lee Crabtree wrote:
Okay, this defies what I would have expected, but a few quick tests make
it look as though chucking the whole list out and re-newing it is almost
twice as fast, viz:
[...]
Running this on my box (2.6 Ghz dual-core) gives between 450 and 650 ms
for the first version, and the second gives between 250 and 400 ms.
The List reference being fast makes sense, as there isn't an amazing
amount of work in generating a reference type, but I was pretty shocked
that creating a great big value array was still faster. Whether this
has to do with the speed of accessing List elements or the speed of
contiguous memory allocation (arrays ARE contiguous, aren't they?) I
don't know, but this was more than a little weird, to my mind.
Well, my first caveat would to note the variance in your timings. If
your tests show differences for the same code of almost 100% (250 to 400
ms), that suggests that there are external factors that have much more
significance than the actual implementation.
That in mind, your results aren't all that surprising to me, as it's
almost always going to be slower to access individual elements than to
do things an entire block of memory at a time. Your second section of
code allows the compiler and run-time to do the latter, and so it seems
reasonably expected that it would be faster.
Pete
Well... List.clear actually calls internally array.clear which is an
internal framework function. I wouldn't be surprised if it didn't
just eventually call some sort of memset variant (which is really
fast).
I would say that calling List.Clear() is going to be slightly faster
than an iterative version (but since her test didn't measure a
List<T>.Clear call it is unclear..pardon the pun).
Really, I think the main advantage to throwing out the old list is the
fact that you can't shrink a list size once it has been grown....and
that every time it grows the array size doubles....So if you have a
list that is 4 megabytes, the next growth will be to 8 megs. even if
you only want 4Megs+2 items....
.
- Follow-Ups:
- Re: Array.Clear vs List<>.Clear
- From: Christof Nordiek
- Re: Array.Clear vs List<>.Clear
- References:
- Array.Clear vs List<>.Clear
- From: Lee Crabtree
- Re: Array.Clear vs List<>.Clear
- From: Nicholas Paldino [.NET/C# MVP]
- Re: Array.Clear vs List<>.Clear
- From: Lee Crabtree
- Re: Array.Clear vs List<>.Clear
- From: Peter Duniho
- Array.Clear vs List<>.Clear
- Prev by Date: Re: DataGrid vs DataGridView
- Next by Date: Re: Array.Clear vs List<>.Clear
- Previous by thread: Re: Array.Clear vs List<>.Clear
- Next by thread: Re: Array.Clear vs List<>.Clear
- Index(es):
Relevant Pages
|