Assuming you are using
CString
you have already done it right by defining the strings outside the loops and assigning empty strings instead of calling
Empty()
which would release the memory.
So the memory of the
CString
objects must be only reallocated when necessary. However, you may pre-allocate memory for all strings using
Preallocate()
with appropriate sizes.
Other optimisations are moving not row related parts out of the row loop, and avoiding calls to
Format()
and
Trim()
:
strQuery = _T("INSERT INTO ");
strQuery += strTName;
strQuery += _T(" ( ");
for ( CXInt nCol = 0; nCol < (CXInt)pMat->NumCols(); nCol++ )
{
if (nCol)
strQuery += _T(',');
strQuery += pMat->GetColumnName(nCol);
}
strQuery += _T(" ) VALUES ( ");
for ( CXInt nFld = 0; nFld < (CXInt)pmatrecordset->NumRows(); nFld++ )
{
strColValues = "";
for ( CXInt nCol = 0; nCol < (CXInt)pMat->NumCols(); nCol++ )
{
if (nCol)
strColValues += _T(',');
strColValues += _T('"');
strColValues += str;
strColValues += _T('"');
}
strColValues += _T(" ) ");
strInsertQuery = strQuery;
strInsertQuery += strColValues;
}
Then most of the execution time should be from the database operations. These can be optimized too by using parametrised commands as already suggested in the comments.
Finally, don't use a debug build when speed matters. Debug builds add a lot of additional code; especially to string operations.