How can I optimize my pathfinding script?

Well, I am not familiar too much with pathfinding myself,
but as far as I understood so far you don’t have to use pathfinding when the player is right in front of you, in that situation you can just use MoveTo()

so you’ll have to raycast and check if the player is visible to the npc, if he was, then you can just use MoveTo(), else you’ll have to use pathfinding!

Also I would suggest you to check out this module which is very helpful

EZ Pathfinding V3 - Resources / Community Resources - DevForum | Roblox