为什么选择比Set语句更快

时间:2012-08-18 06:31:29

标签: c# .net sql sql-server

我做了2次基本测试

1 -

Create Procedure [dbo].[SetLoop]
As Begin 
declare @counter int = 0 ,@a int,@b int,@c int,@d int,@e int
    While @counter < 1000000
    Begin
        set @a=1
        set @b=2
        set @c=3
        set @d=4
        set @e=5
        set @counter = @counter + 1
    End
End

create procedure SelectLoop
As Begin 
declare @counter int =0 ,@a int,@b int,@c int,@d int,@e int
    While @counter < 1000000
    Begin
        select @a=1, @b=2, @c=3, @d=4, @e=5,@counter = @counter + 1
    End
End

    var setTimes = new List<double>();
    for (var i = 0; i < 50; i++)
    {
        stopwatch.Start();
        dataContext.SetLoop();
        stopwatch.Stop();
        setTimes.Add(stopwatch.ElapsedMilliseconds);
        stopwatch.Reset();
    }

    var selectTimes = new List<double>();
    for (var i = 0; i < 50; i++)
    {
        stopwatch.Start();
        dataContext.SelectLoop();
        stopwatch.Stop();
        selectTimes.Add(stopwatch.ElapsedMilliseconds);
        stopwatch.Reset();
    }

    var setAverage = setTimes.Sum() / setTimes.Count;
    var selectAverage = selectTimes.Sum()/selectTimes.Count;

结果

setAverage : 2418.44
selectAverage : 1037.52

setAverage : 2513.8
selectAverage : 1025.98

setAverage : 2496.52
selectAverage : 996.36

结果意味着选择快于one and half时间设置比142.78%

更快

2 -

    While @counter < 1000000
    Begin
        select @a=1
        select @b=2
        select @c=3
        select @d=4
        select @e=5
        select @counter = @counter + 1
    End

    While @counter < 1000000
    Begin
        set @a=1
        set @b=2
        set @c=3
        set @d=4
        set @e=5
        set @counter = @counter + 1
    End

结果

setAverage : 2518.58
selectAverage : 2504.44

setAverage : 2474.5
selectAverage : 2529.48

setAverage : 2511.22
selectAverage : 2514.04

结果意味着它们是相同的

这意味着,如果你需要设置一个变量,将来更喜欢使用Select cuz 你想要添加另一个,@w=3,但是 如果你想要挑衅地设置多个变量,你需要使用Select 它写起来更容易,执行起来更快

但我想知道为什么Select在第一次测试中比Set更快?

1 个答案:

答案 0 :(得分:7)

它不是(至少在你当前的例子中),你为循环的每次迭代运行6个SET语句和一个SELECT语句,因此,我希望SELECT更快。

我建议比较喜欢;

CREATE Procedure [dbo].[SelectLoop]
As Begin 
declare @counter int = 0
    While @counter < 1000000
    Begin
        select @counter = @counter + 1
    End
End

CREATE Procedure [dbo].[SetLoop]
As Begin 
declare @counter int = 0
    While @counter < 1000000
    Begin
       set @counter = @counter + 1
    End
End

这将更准确地指出是否存在差异。