Optimise retain_variable_keys function.