Skip to content

Instantly share code, notes, and snippets.

@krawaller
Created January 27, 2012 18:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krawaller/1690146 to your computer and use it in GitHub Desktop.
Save krawaller/1690146 to your computer and use it in GitHub Desktop.
Compare performance of Titanium Mobile SQLite insert in different ways
// Compare classic insert, insert using Begin/Commit and Union insert described slightly down on this page: http://stackoverflow.com/questions/1609637/is-it-possible-to-insert-multiple-rows-at-a-time-in-an-sqlite-database
// Create some values
var values = [];
for(var i = 0; i < 500; i++){
values.push(i);
values.push(String.fromCharCode(65 + i % 25));
}
// Classic example
var db1 = Titanium.Database.open('tmpdb1');
db1.execute('CREATE TABLE IF NOT EXISTS DATABASETEST (ID INTEGER, NAME TEXT)');
db1.execute('DELETE FROM DATABASETEST');
var before = Date.now();
for(var i = 0; i < 500; i++){
db1.execute('INSERT INTO DATABASETEST (ID, NAME) VALUES(?, ?)', values[i], values[i + 1]);
}
Ti.API.info(' ===== Classic took: ' + (Date.now() - before) + 'ms');
// Begin/Commit
var db2 = Titanium.Database.open('tmpdb2');
db2.execute('CREATE TABLE IF NOT EXISTS DATABASETEST (ID INTEGER, NAME TEXT)');
db2.execute('DELETE FROM DATABASETEST');
db2.execute('BEGIN');
var before = Date.now();
for(var i = 0; i < 500; i++){
db2.execute('INSERT INTO DATABASETEST (ID, NAME) VALUES(?, ?)', values[i], values[i + 1]);
}
db2.execute('COMMIT');
Ti.API.info(' ===== Begin/Commit took: ' + (Date.now() - before) + 'ms');
// Union insert
var db3 = Titanium.Database.open('tmpdb3');
db3.execute('CREATE TABLE IF NOT EXISTS DATABASETEST (ID INTEGER, NAME TEXT)');
db3.execute('DELETE FROM DATABASETEST');
db3.execute.call = Function.prototype.call;
db3.execute.apply = Function.prototype.apply;
db3.insert = function(o){
var str = ['INSERT INTO ', o.into, ' SELECT ? AS ', o.cols.join(", ? AS "), (new Array(o.values.length/o.cols.length)).join(' UNION SELECT ?' + (new Array(o.cols.length)).join(', ?'))].join("");
db3.execute.apply(db3, [str].concat(o.values));
};
var before = Date.now();
db3.insert({into: 'DATABASETEST', cols: ['ID', 'NAME'], values: values });
Ti.API.info(' ===== Union insert took: ' + (Date.now() - before) + 'ms');
}, 3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment