efficency question

  • Thread starter Thread starter philipl
  • Start date Start date
P

philipl

which is more efficient for looking up an element in an arraylist? An
Arraylist.Contains? or Go throught it with a while or for loop?

thx
 
which is more efficient for looking up an element in an arraylist? An
Arraylist.Contains? or Go throught it with a while or for loop?

I would imagine ArrayList.Contains is at least as efficient as anything
else, but more important is that it clearly states what you're after,
in a concise way. Always go for readability until you've got a reason
to believe that one piece of code is acting as a bottleneck.
 
which is more efficient for looking up an element in an arraylist? An
Arraylist.Contains? or Go throught it with a while or for loop?

ArrayList.Contains effectivly just uses a for loop(with some null logic) to
search through its contents, so the actual efficiency difference as far as
the algorithm goes is small. However, by all indications Contains directly
accesses the underlying array instead of using the indexer(which is virtual
and can't be inlined). As a result of this, in tight loops Contains may be
the better option, although arguably in tight loops using a local array may
be a better idea as well. This is pure speculation, however, and would
require you to perform your own tests to be sure.

However, for reasons of clarity, I would suggest using Contains no matter
what benchmarks show. The efficency\performance difference is highly
negligible in all but the most extreme cases.
 
However, for reasons of clarity, I would suggest using Contains no matter
what benchmarks show. The efficency\performance difference is highly
negligible in all but the most extreme cases.

yes, and remember the two rules of optimization:

1. Don't do it
2. (for experts only) Don't do it yet.

:)
 
Back
Top