Good way to cull off-screen sprite animations

I'm creating a tile based platformer in Lua, and there are a lot of spikes, which have a simple animation. Each spike is a separate sprite, and they all have an update function that simply sets the new image from the animation loop

I found with a lot of spikes in a level, it was causing a big performance hit, because spikes that were off-screen were being animated. I ended up doing this to filter them out, which greatly helps performance, but was wondering if there's a better way, like maybe a sprite attribute that can disable the update function automatically when the sprite is off screen.

function Spike:update()
	local offsetX, offsetY = gfx.getDrawOffset()
	
	if self.x + self.width >= -offsetX and self.x <= -offsetX + 400 then
		self:setImage(spikeImage:image())
	end
end

Thanks in advance for any ideas.

Assuming the spikes don’t move, have you considered putting them in a tilemap and swapping out the tilemap’s image table to animate the whole level? That would at least get rid of the update logic although I’m not sure how performant it is otherwise.

Oooh that's an interesting idea. Some of the spikes are flipped, so I'd have to work around that. But I may look into it. Thanks!

After trying a few other things I ended up just adding another little check, and now with a ton of spikes on screen I might lose 1 or 2 frames, but it's not bad.

I realized I was assigning a new image to the sprite each update when the animation hadn't even changed, and maybe there's a better way, but here's basically what I ended up with:

if self.currentFrame ~= spikeImage.frame then
	self:setImage(spikeImage:image())
	self.currentFrame = spikeImage.frame
end