开发者

For Each loop enumerator expression and memory consumption

According to the language specification guide for VB.NET Section 10.9.3

The enumerator expression in a for each l开发者_开发知识库oop is copied over into memory.

If I have a list of 10000 objects that list will be in memory twice for the code below?

dim myList as new list(of bobs)
'put 10000 bobs in my list
for each x In myList
'do something 
next

If I were generating the list from a linqQuery or some other such query it would make sense to generate that list at the for each loop statement thus not having the list in memory twice for example.

for each x in myList.where(function(x) x.name = Y)
'do something
next

If the LINQ query is unreadable on the for each loop, do I forgo readability and just put it on the for each loop declaration line?

Should I declare the list in its own variable and just bite the bullet and have the list exist twice in memory?


that list will be in memory twice for the code below

No, it won't. In your case, the spec is talking about the variable "x" here - not the entire collection. Remember, and enumerator (any IEnumerable<T> or similar) doesn't necessarily even have items in memory. When created via an iterator in C#, for example, you can have "collections" that are generated as you enumerate over them. There isn't a "list" of objects (necessarily) that could be copied, even if the language wanted to do so.

Is the linq query is unreadable on the for each loop

In many cases, I prefer filtering this way. You can just as easily move this outside of the loop, if you want to make it more clear, as well:

Dim filteredCollection = myList.Where(Function(x) x.name = Y)
For Each x in filteredCollection

There is no disadvantage to doing this if you find it more readable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜