improve performance in constructing weight matrix