c++: port over optimisation from go (d2e03a38c739006398ee0d6eef75bf10e25000ce)