trying to speed up D2 calculation by using less memory