Is the code slower? Yes, slightly. For old mobile GPUs that was a concern, but today adding a few extra instructions isn’t really a huge issue. We’re at the point where shaders can be several hundred to over a thousand instructions … and that’s fine. So in that context adding a few here and there to avoid possible issues isn’t a huge deal.
And yes, avoiding NaNs is something you want to do. All GPUs handle NaNs correctly, which is to say any math operation where one input is a NaN results in a NaN. That is the correct way to handle a NaN, because it’s not a number. Similarly inf values can spread because almost any math operation where one input is an infinite the result is an infinite.
So you want to avoid things that may create either of them, or at the very least suppress them. Especially since with modern rendering where there’s a lot of post processing, that NaN or inf can very easily spread. The result of not taking some effort to suppress these kinds of values in places where they may occur can be things like the entire screen slowly (or quickly!) being overtaken by a solid black or white color, or in the best case single frame flashes of black or white.
In Unity’s built in renderer, some setups using directional lightmaps and the Post Processing Stack can cause large white squares to flicker across screen the when moving the camera, as Unity’s directional lightmap shaders have some unsafe code that can produce infs or NaNs.
In the HDRP people have had issues where solid black squares seem to spread across the screen as some normal mapping code (like the above w/o the protection) could produce bad values.
And it’s not just Unity. Here’s an example of this kind of issue showing up in Super Mario Odyssey on the Switch:
World or object space normal maps in particular are a frequent source of the problem, as the normal directions are interpolated vectors. It’s entirely possible for the vector to point in opposite directions between two texels, resulting in an interpolated vector of 0,0,0 showing up.
These weren’t really an issue on older GPUs, not because those shaders didn’t also produce NaN and inf values, but because older games didn’t output to HDR floating point render targets. The bad values would be automatically clamped to 0.0 or 1.0 when they wrote to the render target as the image formats being used didn’t support anything outside of that range. But with modern HDR rendering, and writing to floating point render targets, those will retain NaN and inf values.