This loop is slower than I would expect, and I'm not sure where yet. See anything?
I'm reading an Accces DB, using client-side cursors. When I have 127,000 rows with 20 columns, this loop takes about 10 seconds. The 20 columns are string, int, and date types. All the types get converted to ANSI strings before they are put into the ostringstream buffer.
void LoadRecordsetIntoStream(_RecordsetPtr& pRs, ostringstream& ostrm)
{
ADODB::FieldsPtr pFields = pRs->Fields;
char buf[80];
::SYSTEMTIME sysTime;
_variant_t var;
while(!pRs->EndOfFile) // loop through rows
{
for (long i = 0L; i < nColumns; i++) // loop through columns
{
var = pFields->GetItem(i)->GetValue();
if (V_VT(&var) == VT_BSTR)
{
ostrm << (const char*) (_bstr_t) var;
}
else if (V_VT(&var) == VT_I4
|| V_VT(&var) == VT_UI1
|| V_VT(&var) == VT_I2
|| V_VT(&var) == VT_BOOL)
{
ostrm << itoa(((int)var),buf,10);
}
else if (V_VT(&var) == VT_DATE)
{
::VariantTimeToSystemTime(var,&sysTime);
_stprintf(buf, _T("%4d-%02d-%02d %02d:%02d:%02d"),
sysTime.wYear, sysTime.wMonth, sysTime.wDay,
sysTime.wHour, sysTime.wMinute, sysTime.wSecond);
ostrm << buf;
}
}
pRs->MoveNext();
}
}
EDIT: After more experimentation...
I know now that about half the time is used by this line:
var = pFields->GetItem(i)->GetValue();
If I bypass the Microsoft generated COM wrappers, will my code be faster? My guess is no.
The othe half of the time is spent in the statements which convert data and stream it into the ostringstream.
I don't know right now as I write this whether it's the conversions or the streaming that is taking more time.
Would it be faster if I didn't use ostringstream and instead managed my own buffer, with my own logic to grow the buffer (re-alloc, copy, delete)? Would it be faster if my logic made a pessimistic guesstimate and reserved a lot of space for the ostringstream buffer up front? These might be experiments worth trying.
Finally, the conversions themselves. None of the three stand out in my timings as being bad. One answer says that my itoa might be slower than an alternative. Worth checking out.