Optimize swapping function