PR ReviewThe simple stuff will trip you

time to read 2 min | 285 words

In a recent PR, I run into this code, which is used in query generation to decide if we need to quote a particular alias. The code itself is pretty straightforward and easy to follow:

image

image

It also have two distinct issues. First, there is the allocation because of the ToUpper call and second, we are doing O(N) search on the alias array every single time.

I asked for a change, to use HashSet and to use the OrdinalIgnoreCase comparer.

Here is the change I got back:

image

image

This is exactly what I asked for, and it is very subtly wrong. We are now saving an allocation, which is great, but the problem is with the Contains method.

image

This looks okay, but this is not HashSet.Contains, instead, this is an extension method from Enumerable.Contains, which iterates over the set and compare each value.

The fix is also simple:

image

image

And now we don’t have O(N) anymore.

Although I’ll admit that for such small size, it probably doesn’t matter.

More posts in "PR Review" series:

  1. (19 Dec 2017) The simple stuff will trip you
  2. (08 Nov 2017) Encapsulation stops at the assembly boundary
  3. (25 Oct 2017) It’s the error handling, again
  4. (23 Oct 2017) Beware the things you can’t see
  5. (20 Oct 2017) Code has cost, justify it
  6. (10 Aug 2017) Errors, errors and more errors
  7. (21 Jul 2017) Is your error handling required?
  8. (23 Jun 2017) avoid too many parameters
  9. (21 Jun 2017) the errors should be nurtured