Generic UDF and performance improvements