optimize the nextkey function