Is there a way to optimize this piece of code?

No. But there might be memory issues with this approach if the number of atlases keeps growing or if they are large. This is discussed here: