Some small performance and thread safety improvements