0

kindly enlightened me, which is faster/better approach or just the same between CI batch insert and loop insert.

$data = array(
          array(
               'title' => 'My title' ,
               'name' => 'My Name' ,
               'date' => 'My date'
          ),
          array(
             'title' => 'Another title' ,
             'name' => 'Another Name' ,
             'date' => 'Another date'
          )
         );


batch insert:

   $this->db->insert_batch('mytable', $data); 

  /* produces: INSERT INTO mytable (title, name, date) 
          VALUES ('My title', 'My name', 'My date'), 
                 ('Another title', 'Another name', 'Another date'); */


loop insert (php):

 for( $i = 0; $ < count($data); $i++ )
 {
    INSERT INTO mytable (title, name, date) 
    VALUES ($data[$i]['title'], $data[$i]['name'], $data[$i]['date'])
 }

thanks!

2
  • 1
    I would recommend a batch insert, or an insert with transactions, where you run all your inserts before comitting. Commented Feb 5, 2014 at 3:12
  • 4
    The batch should be faster. Each call to insert has overhead associated with it. One insert with many rows is normally faster. Commented Feb 5, 2014 at 3:30

1 Answer 1

4

Batch inserts are usually faster since they process the data in once, were as the INSERT has some overhead (eg, the SQL optimizer cannot deduct certain steps). That said, you need to process a tremendous number of rows to create a notable difference.

If your curious if it would matter anyway, then don't forget to also measure the time it costs the framework to map the classes to the database table(s). There's a good chance the ORM consumes more resources than a looped SQL INSERT.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.