Cherry-pick dorian's optimizations

I tried my first cherry-picking, so that we would avoid the somewhat mixed up branches, and did a very trivial test on my FOAF file, and yeah, it is a bit faster.

Kjetil