Relative Performance in SQLServer of Substring vs a Right-Left combo

后端 未结 1 452
耶瑟儿~
耶瑟儿~ 2021-01-11 19:06

This is a performance based question, not a \"I don\'t understand\" or \"best practice\" question.

I have a varchar field in a SQLServer database th

相关标签:
1条回答
  • 2021-01-11 19:20

    +1 for an interesting question. Your assessment that SQL Server may significantly change each statement through optimization is probably accurate; same as your assessment that in such a large set SQL Server may be able to cache one query better than another.

    Two other things come to mind that might be (vaguely) relevant:

    • Memory consumption; I would be curious if the LEFT/RIGHT combo consumes slightly more memory. In theory, the return value of the first function would need to be stored so that it could be passed into the second function, though the same register might be used over and over.

    • Bounds checking. A varchar is basically a pointer to the beginning of a char[] with 2 extra bytes for indicating length. This suggests that some sort of bounds checking would need to be performed when accessing a value by an index by looking at the value contained in those 2 bytes to make sure it wasn't out of range.

    SQL Server is also very forgiving when making requests outside the limits of the string with both chars and varchars. The following code will run without any errors.

    DECLARE @Test varchar(50);
    SET @Test = 'Hello World';
    SELECT substring(@Test, 2, 4);
    SELECT substring(@Test, 2000, 5000);
    

    So will:

    SELECT right(left(@test, 500), 400);
    

    My guess is that the explanation for the answer to your question lies in something related; unfortunately I don't know the answer to your question.

    I would be curious if you got the same performance results using a longer string, or a char versus a varchar. Those tests could yield more insights into the internals of SQL Server.

    0 讨论(0)
提交回复
热议问题