Improve memory management: malloc is a heavy operation, do less of it to make transitions less CPU intensive

Signed-off-by: Mattias Andrée <maandree@operamail.com>