score:0

i recently found myself wondering whether i've been totally spoiled by linq. yes, i now use it all the time to pick all sort of things out from all sort of collections.

score:0

i started to, but found out in some cases, i saved time by using this approach:

for (var i = 0, len = list.count; i < len; i++) { .. }

not necessarily in all cases, but some. most extension methods use the foreach approach of querying.

score:0

i try to follow these rules:

  • whenever i'm just querying (filtering, projecting, ...) collections, use linq.
  • as soon as i'm actually 'doing' something with the result (i.e, introduce side effects), i'll use a for loop.

so in this example, i'll use linq.

also, i always try to split up the 'query definition' from the 'query evaluation':

dim query = from r in table.asenumerable() 
            select r.field(of integer)("id")

dim result = query.tolist()

this makes it clear when that (in this case in-memory) query will be evaluated.

score:1

i avoid linq unless it helps readability a lot, because it completely destroys edit-and-continue.

when they fix that, i will probably start using it more, because i do like the syntax a lot for some things.

score:1

for almost everything i've done i've come to the conclusion that linq is optimized enough. if i handcrafted a for loop it would have better performance, but in the grand scheme of things we are usually talking milliseconds. since i rarely have a situation where those milliseconds will make any kind of impact, i find it's much more important to have readable code with clear intentions. i would much rather have a call that is 50ms slower than have someone come along and break it altogether!

score:1

resharper has a cool feature that will flag and convert loops into linq expressions. i will flip it to the linq version and see if that hurts or helps readability. if the linq expression more clearly communicates the intent of the code, i will go with that. if the linq expression is unreadable, i will flip back to the foreach version.

most of the performance issues don't really compare with readability for me.

clarity trumps cleverness.

in the above example, i would go with the the linq version since it clearly explains the intent and also locks out people accidently adding side effects in the loop.

score:5

whenever possible i favor the declarative way of programming instead of imperative. when you use a declarative approach the clr can optimize the code based on the characteristics of the machine. for example if it has multiple cores it could parallelize the execution while if you use an imperative for loop you are basically locking this possibility. today maybe there's no big difference but i think that in the future more and more extensions like plinq will appear allowing better optimization.


Related Query

More Query from same tag