Insertion of thousands of contact entries using applyBatch is slow

后端 未结 7 2021
我在风中等你
我在风中等你 2020-11-28 23:02

I\'m developing an application where I need to insert lots of Contact entries. At the current time approx 600 contacts with a total of 6000 phone numbers. The biggest contac

7条回答
  •  情深已故
    2020-11-28 23:17

    bulkInsert: For those interested, here is the code that I was able to experiment with. Pay attention to how we can avoid some allocations for int/long/floats :) this could save more time.

    private int doBulkInsertOptimised(Uri uri, ContentValues values[]) {
        long startTime = System.currentTimeMillis();
        long endTime = 0;
        //TimingInfo timingInfo = new TimingInfo(startTime);
    
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    
        DatabaseUtils.InsertHelper inserter =
            new DatabaseUtils.InsertHelper(db, Tables.GUYS); 
    
        // Get the numeric indexes for each of the columns that we're updating
        final int guiStrColumn = inserter.getColumnIndex(Guys.STRINGCOLUMNTYPE);
        final int guyDoubleColumn = inserter.getColumnIndex(Guys.DOUBLECOLUMNTYPE);
    //...
        final int guyIntColumn = inserter.getColumnIndex(Guys.INTEGERCOLUMUNTYPE);
    
        db.beginTransaction();
        int numInserted = 0;
        try {
            int len = values.length;
            for (int i = 0; i < len; i++) {
                inserter.prepareForInsert();
    
                String guyID = (String)(values[i].get(Guys.GUY_ID)); 
                inserter.bind(guiStrColumn, guyID);
    
    
                // convert to double ourselves to save an allocation.
                double d = ((Number)(values[i].get(Guys.DOUBLECOLUMNTYPE))).doubleValue();
                inserter.bind(guyDoubleColumn, lat);
    
    
                // getting the raw Object and converting it int ourselves saves
                // an allocation (the alternative is ContentValues.getAsInt, which
                // returns a Integer object)
    
                int status = ((Number) values[i].get(Guys.INTEGERCOLUMUNTYPE)).intValue();
                inserter.bind(guyIntColumn, status);
    
                inserter.execute();
            }
            numInserted = len;
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            inserter.close();
    
            endTime = System.currentTimeMillis();
    
            if (LOGV) {
                long timeTaken = (endTime - startTime);
                Log.v(TAG, "Time taken to insert " + values.length + " records was " + timeTaken + 
                        " milliseconds " + " or " + (timeTaken/1000) + "seconds");
            }
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return numInserted;
    }
    

提交回复
热议问题