This function avoids some unecessary memory allocation. The memory alloc'd by this function must be freed later by the caller. (cherry picked from commit 8651174861)
8651174861