Reduce the amount of work during a lock.

 This pull request will introduce changes to improve performance.
 The lock is only held when manipulating data structures.