Backported some of the optimizations from unsafe solution. Co-authored-by: Giedrius D <d.giedrius@gmail.com>