zoukankan      html  css  js  c++  java
  • rails 批量写入数据的效率

      最近用到批量生成大量数据,为避免客户端产生假死的状态,因此测试了以下几种方式的效率

    def test1
      params=[]
      puts Time.now
      10000.times do |i|
        e_quiz = ExaminationQuiz.new
        e_quiz.examination_id = 1
        e_quiz.quiz_id = i
        params.push(e_quiz)
      end
      puts Time.now
      ExaminationQuiz.create(params)
      puts Time.now
    end
    def test2
      params=[]
      s = Examination.first
      puts Time.now
      10000.times do |i|
        
        s.examination_quizzes.create(:quiz_id=>i) 
        end
      puts Time.now
    end
    
    

     

    def test3
      params=[]
     con = ActiveRecord::Base.connection()
      puts Time.now
      10000.times do |i|
        params.push("('title',6,1,1,'',1,'','true',1,1,'#{Time.now.to_s(:db)}','#{Time.now.to_s(:db)}')")
      end
      sql = "INSERT INTO examination_quizzes (title,user_id,examination_id,quiz_id,quiz_type,submit_answer_id,submit_answer_name,is_correct,level_id,position,created_at,updated_at)VALUES #{params.join(", ")}"
      puts Time.now
      con.insert sql
      puts Time.now
    end
    

      

     

      测试结果如下:

    ruby-1.9.2-p180 :118 >   test1
    Tue, 23 Oct 2012 16:35:42 +0800
    Tue, 23 Oct 2012 16:35:43 +0800
    Tue, 23 Oct 2012 16:36:06 +0800
     => nil 
    ruby-1.9.2-p180 :119 > test3
    Tue, 23 Oct 2012 16:36:11 +0800
    Tue, 23 Oct 2012 16:36:13 +0800
    Tue, 23 Oct 2012 16:36:13 +0800
     => nil 
    ruby-1.9.2-p180 :120 > test2
    Tue, 23 Oct 2012 16:36:54 +0800
    Tue, 23 Oct 2012 16:39:04 +0800
     => nil 

      有结果可以看出,使用sql批量创建数据的速度最快!

  • 相关阅读:
    TypeConverter的使用
    ASP.NET MVC——Controller的激活
    ASP.NET 会话状态的模式
    ASP.NET页面生命周期描述
    一个字符串搜索的Aho-Corasick算法
    ILMerge 简单使用
    js css优化-- 合并和压缩
    C#.Net网页加载等待效果漂亮并且简单
    获取打开文件的路径和文件名
    C#程序中:如何启用进程、结束进程、查找进程
  • 原文地址:https://www.cnblogs.com/yanmiao/p/2735768.html
Copyright © 2011-2022 走看看