5

我做了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
选择平均:1037.52

setAverage : 2513.8
选择平均:1025.98

setAverage : 2496.52
选择平均:996.36

结果意味着 Select 比 Set by one and halftime快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
选择平均:2504.44

setAverage : 2474.5
选择平均:2529.48

setAverage : 2511.22
选择平均:2514.04

结果意味着它们是相同的

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

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

4

1 回答 1

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

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

于 2012-08-18T06:37:41.750 回答