ActiveRecord query much slower than straight SQL?

前端 未结 1 1242
故里飘歌
故里飘歌 2021-02-08 17:25

I\'ve been working on optimizing my project\'s DB calls and I noticed a \"significant\" difference in performance between the two identical calls below:

connecti         


        
1条回答
  •  醉梦人生
    2021-02-08 18:17

    A couple of things jump out.

    Firstly, if this code is being called 2000 times and takes 250ms extra to run, that's ~0.125ms per call to convert the Arel to SQL, which isn't unrealistic.

    Secondly, I'm not sure of the internals of Range in Ruby, but lower..upper may be doing calculations such as the size of the range and other things, which will be a big performance hit.

    Do you see the same performance hit with the following?

    sum = Table.
          where(:id => id).
          where(:created_at => "BETWEEN ? and ?", lower, upper).
          sum(:my_column)
    

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