Add consts in a few places where it makes sense, avoid unnecessary memory reallocation where we know the full size needed at the outset, simplify and avoid memory copy.