Reputation: 37000
I have a code using third-party-tool iterating over a collection of points.
for (int i = 0; i < pcoll.PointCount; i++) { /* ... */ }
When doing profiling via dotTrace I noticed that the PointCount
-proerty is accessed every iteration (see picture above)
.
I expected that the value for this property is optimized away by the compiler but obviously that doesn't happen. Maybe this is actually a problem within the COM-based 3rd-party lib or also within dotTrace self when collecting the information.
I'm not sure if this topic wouldn't fit better to Gis.StackExchange. However maybe someone has any idea under which circumstances optimzation won't take place or how it might happen.
Upvotes: 4
Views: 134
Reputation: 21969
The expected optimization is true for fields. But property has setter/getter (accessing property is in fact calling them as methods), so compiler will have hard time to try to optimize it.
To fix, make it a field or read it once
var max = pcoll.PointCount;
for (int i = 0; i < max; i++) { /* ... */ }
Upvotes: 1
Reputation: 113232
It may have changed in the meantime.
Indeed, one of the reasons to test i < pcoll.PointCount
every iteration rather than just using foreach(var point in pcoll)
is precisely because you think the collection might change in the meantime, and enumerators don't guarantee to cope with changes to the collection they enumerate.
This differs from, for example, an array accessed through a local variable, because the only way the Length
of an array accessed through a local variable can change, is if the change is made locally.
Even there though, it's worth remembering that the compiler often skips some obvious optimisations because it's known that the jitter makes the same optimisation too.
Upvotes: 2
Reputation: 43254
Simply put, how is the compiler to know whether pcoll.PointCount
will change between invocations? It can't safely make the assumption that the value will remain unchanged, so it can't optimise this code by caching the value of the first call to pcoll.PointCount
.
Upvotes: 7