我正在进行一些性能测试,发现了一个我无法解释的结果。我以两种方式实现相同的逻辑:T-SQL UDF和.Net CLR功能。这是源代码:
标量UDF:
create or alter function dbo.ParticularDateFormat(@inputDate date) returns char(14) as begin declare @return char(14) set @return = cast(DATEPART(dd, @inputdate) as char(2)) + ' ' + choose(datepart(mm, @inputDate), 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dez') + ' ' + cast(DATEPART(yyyy, @inputDate) as char(4)) return @return end
.Net CLR功能
[SqlFunction(IsDeterministic = true)] public static SqlString NewDateStyle(SqlDateTime inputDate) { return ((DateTime)inputDate).ToString("dd MMM yyyy"); }
然后我在100万行表上运行这两个函数。当我运行标量UDF时,我得到这个统计时间反馈:
SQL Server Execution Times: CPU time = 0 ms, elapsed time = 0 ms. SQL Server parse and compile time: CPU time = 0 ms, elapsed time = 0 ms. (1000000 row(s) affected) Table 'SmallTable'. Scan count 1, logical reads 1616, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. (1 row(s) affected) SQL Server Execution Times: CPU time = 3734 ms, elapsed time = 4587 ms.
这是我运行.Net CLR功能时的统计时间反馈:
SQL Server Execution Times: CPU time = 0 ms, elapsed time = 0 ms. SQL Server parse and compile time: CPU time = 141 ms, elapsed time = 191 ms. (1000000 row(s) affected) Table 'SmallTable'. Scan count 1, logical reads 1616, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. (1 row(s) affected) SQL Server Execution Times: CPU time = 1312 ms, elapsed time = 3586 ms. SQL Server parse and compile time: CPU time = 0 ms, elapsed time = 0 ms. SQL Server Execution Times: CPU time = 0 ms, elapsed time = 0 ms.
正如预期的那样.Net CLR功能运行速度更快。
我无法理解的是经过时间过长的原因,几乎是处理查询时间的两倍(CPU时间)。
有什么想法吗?