Good evening, and thanks to your excellent Postgres.
This funcion in used as a column in a select on about 400k records
If I leave the highlighted row it takes 27 seconds, otherwise 14 seconds! Such behaviour looks not to be reasonable.
lightly testing this, I got 10million iterations in about two seconds, about the same after commenting the NaN test. Given that, problem is probably failure to inline query. Careful examination of explain of wrapping query should prove that.