Reducing DatabaseServer’s Excessive Memory Allocation

Joined
Jun 9, 2016
Messages
51
Reaction score
72
Hello everyone!
I recently noticed that the allocated memory in the DatabaseServer is much higher than the actually used memory (if you have an expanded inventory you’ll see a huge difference).
Here’s a screenshot from VS Diagnostics (it shows the total memory allocated by the application):


Without fix - Reducing DatabaseServer’s Excessive Memory Allocation - RaGEZONE Forums
With fix - Reducing DatabaseServer’s Excessive Memory Allocation - RaGEZONE Forums


  • 310 MB RAM (without expanded slots) → 105 MB
  • 1.4 GB RAM (with 168 slots / ~51,000 characters) → 105 MB
Since the default executables are built as x86 (32-bit) without the Large Address Aware flag, once allocated memory exceeds 2 GB the .exe will simply crash.

I propose this fix to reduce the allocated memory:
This code is 100% compatible with C++14 and later.

Query.h

C++:
#ifdef __QS_FIX_ALLOCATED_MEM
#ifdef __INVENTORY_168_SLOTS
    static const int MAXSYM = 51000;
#else
    static const int MAXSYM = 8192;
#endif
    std::vector<std::array<char, MAXSYM>> Col;
#else
    char*    Col[MAXCOL];
#endif
And:
C++:
#ifdef __QS_FIX_ALLOCATED_MEM
    std::vector<std::array<SQLCHAR, 50>> ColName;
    std::vector<SQLINTEGER> lCol;
#else
    SQLCHAR ColName[MAXCOL][50];
    SQLINTEGER lCol[MAXCOL];
#endif
Query.cpp
In CQuery::CQuery()
Replace:
C++:
#ifdef __INVENTORY_168_SLOTS
    for (int i = 0; i < MAXCOL; i++)
        Col[i] = new char[51000];
#else
    for (int i = 0; i < MAXCOL; i++)
        Col[i] = new char[8192];
#endif
To:
C++:
#ifndef __QS_FIX_ALLOCATED_MEM
#ifdef __INVENTORY_168_SLOTS
    for (int i = 0; i < MAXCOL; i++)
        Col[i] = new char[51000];
#else
    for (int i = 0; i < MAXCOL; i++)
        Col[i] = new char[8192];
#endif
#endif
In CQuery::~CQuery()
Replace:
C++:
for(int i = 0; i < MAXCOL; i++)
       SAFE_DELETE_ARRAY( Col[i] );
To:
C++:
#ifndef __QS_FIX_ALLOCATED_MEM
    for(int i = 0; i < MAXCOL; i++)
        SAFE_DELETE_ARRAY( Col[i] );
#endif
In CQuery::FindCol(char *name)
Replace:
C++:
if (stricmp(name,(LPCTSTR)ColName[i])==0)
To:
C++:
#ifdef __QS_FIX_ALLOCATED_MEM
        if (stricmp(name, (LPCTSTR)ColName.at(i).data()) == 0)
#else
        if (stricmp(name,(LPCTSTR)ColName[i])==0)
#endif
In CQuery::GetInt(int nCol)
Replace:
C++:
return atoi(Col[nCol-1]);
To:
C++:
#ifdef __QS_FIX_ALLOCATED_MEM
        return atoi(Col.at(nCol - 1).data());
#else
        return atoi(Col[nCol-1]);
#endif
In __int64 CQuery::GetInt64(int nCol)
Replace:
C++:
return _atoi64(Col[nCol-1]);
To:
C++:
#ifdef __QS_FIX_ALLOCATED_MEM
        return _atoi64(Col.at(nCol - 1).data());
#else
        return _atoi64(Col[nCol-1]);
#endif
In float CQuery::GetFloat(int nCol)
Replace:
C++:
return    ( (float)( atof(Col[nCol-1]) ) );
To:
C++:
#ifdef __QS_FIX_ALLOCATED_MEM
        return((float)(atof(Col.at(nCol - 1).data())));
#else
        return    ( (float)( atof(Col[nCol-1]) ) );
#endif
In char CQuery::GetChar(int nCol)
Replace:
C++:
return Col[nCol-1][0];
To:
C++:
#ifdef __QS_FIX_ALLOCATED_MEM
        return Col.at(nCol - 1).data()[0];
#else
        return Col[nCol-1][0];
#endif
In void CQuery::GetStr(int nCol, char *buf)
Replace:
C++:
strcpy(buf,Col[nCol-1]);
To:
C++:
#ifdef __QS_FIX_ALLOCATED_MEM
         strcpy(buf, Col.at(nCol - 1).data());
#else
         strcpy(buf,Col[nCol-1]);
#endif
In BOOL CQuery::PrepareFetch()
After:
C++:
    SWORD    m_nNullability;
Add:
C++:
#ifdef __QS_FIX_ALLOCATED_MEM
    if(nCol > static_cast<SQLSMALLINT>(Col.size()))
        Col.resize(nCol);
    if(nCol > static_cast<SQLSMALLINT>(ColName.size()))
        ColName.resize(nCol);
    if(nCol > static_cast<SQLSMALLINT>(lCol.size()))
        lCol.resize(nCol);
#endif
Replace:
C++:
#ifdef __INVENTORY_168_SLOTS
        SQLBindCol(hStmt, c + 1, SQL_C_CHAR, Col[c], 51000, &lCol[c]);
#else
        SQLBindCol(hStmt, c + 1, SQL_C_CHAR, Col[c], 8192, &lCol[c]);
#endif
        SQLDescribeCol(hStmt,c+1,ColName[c],30,
To:
C++:
#ifdef __QS_FIX_ALLOCATED_MEM
        SQLBindCol(hStmt, c + 1, SQL_C_CHAR, Col.at(c).data(), MAXSYM, &lCol[c]);
        SQLDescribeCol(hStmt,c+1,ColName.at(c).data(), 30,
#else
#ifdef __INVENTORY_168_SLOTS
        SQLBindCol(hStmt, c + 1, SQL_C_CHAR, Col[c], 51000, &lCol[c]);
#else
        SQLBindCol(hStmt, c + 1, SQL_C_CHAR, Col[c], 8192, &lCol[c]);
#endif
        SQLDescribeCol(hStmt,c+1,ColName[c],30,
#endif
StdAfx.h (AccountServer, Certifier and DatabaseServer)
After:
C++:
#include <vector>
Add:
C++:
#include <array>
VersionCommon.h (AccountServer, Certifier and DatabaseServer) or to a common file
Add:
C++:
#define __QS_FIX_ALLOCATED_MEM


P.S. This code has been tested for about two months on two local servers and one live (beta) server.
I would appreciate it if you could let me know of any errors or shortcomings in the code.
 
Last edited:
Doesn't it go up on the amount of connections (player count)?
This change simply replaces pre-allocated static memory (arrays) with dynamic memory (vectors), so that only as much memory as is actually needed (or slightly more, due to how vectors works) is allocated. Most CQuery don't even use 25% of the memory allocated for them. Moreover, CQuery doesn't depend on the number of players or anything like that - it is created when the thread is initialized (for example, in CDbManager::GetThread()) and is used for the whole thread after that.

P.S Memory usage will indeed increase slightly on the live server, but at a certain point, it will expand to the maximum required size and then stop allocating further. Additionally, thanks to this code, CQuery can be created more frequently since it won’t need to allocate a huge amount of memory upon creation.
 
Last edited:
P.S Memory usage will indeed increase slightly on the live server, but at a certain point, it will expand to the maximum required size and then stop allocating further.
And not to the old values (1.5 GB), much less, I think no more than 250-300 MB (if starting from 100 MB)

Doesn't it go up on the amount of connections (player count)?
You can start the server, enable debugging DatabaseServer (alt + ctrl + P) and see that the RAM consumption (in Diagnostics) from the start is ~1.5 GB (168 slots) and ~350 MB (default)
 
Last edited:
At first I thought, "maybe this would introduce more memory fragmentation" but then I remembered, well not always.

My suggestion is to determine the lifetime of the CQuery object. If there are CQuery objects that are persistent through the application, is that object changing the query called or reused? If you don't have to continually reallocate the storage space or even check space of the columns within the CQuery object, then it's more acceptable.

You should also be handling your check in PrepareStatement with this: (This might seem picky but it showcases more to the user rather than "just declare it after a variable being made but not set")
C++:
SQLNumResultCols(hStmt,&nCol);
    if (nCol > MAXCOL)
        return FALSE;

But, you also remove the use for MAXCOL in theory, so this check wouldn't be required anymore. Proof of that would be in the IBM and microsoft documentation related to using the mssql connector: 'The function sets the output argument to zero if the last statement or function executed on the input statement handle did not generate a result set. "If the statement associated with StatementHandle does not return columns, SQLNumResultCols sets *ColumnCountPtr to 0." (You could keep using it as an artificial limit to ensure maximum columns returned is lower than 255).


To my first point again, I believe some CQuery objects that run use and utilize multiple sql statements -- so the PrepareFetch may have to resize the allocation multiple times in relation to that which would introduce possible memory fragmentation due to having to resize the vector more than once.

You could write a custom container to store some of the information on the stack or something similar to avoid pointer dereferencing and heap allocations for a little bit. E.g: SmallQuery or something similar. I like using stack allocated space for smaller based queries as it'd be faster, and it'd skip having to dynamically allocate that memory.

I brought up MAXCOL earlier because Flyff doesn't use up to it or not even close to it. Increasing the allocation of those char pointers for the inventory isn't necessary at all, you could just utilize more columns. This also keeps it working with older odbc settings where VARCHAR MAX doesn't bind properly to the variables. Just going back to the non 168 inventory version will drastically decrease memory allocation. (Bonus, flyff doesnt do anything with blobs, so no need to write a blob reader either).

Then another thing that would be nice is using another struct or something to separate lCol, Col and ColName. lCol either being strlen length or an indicator for the fetch statement. I only bring that up because of so many similar names.
 
At first I thought, "maybe this would introduce more memory fragmentation" but then I remembered, well not always.

My suggestion is to determine the lifetime of the CQuery object. If there are CQuery objects that are persistent through the application, is that object changing the query called or reused? If you don't have to continually reallocate the storage space or even check space of the columns within the CQuery object, then it's more acceptable.

You should also be handling your check in PrepareStatement with this: (This might seem picky but it showcases more to the user rather than "just declare it after a variable being made but not set")
C++:
SQLNumResultCols(hStmt,&nCol);
    if (nCol > MAXCOL)
        return FALSE;

But, you also remove the use for MAXCOL in theory, so this check wouldn't be required anymore. Proof of that would be in the IBM and microsoft documentation related to using the mssql connector: 'The function sets the output argument to zero if the last statement or function executed on the input statement handle did not generate a result set. "If the statement associated with StatementHandle does not return columns, SQLNumResultCols sets *ColumnCountPtr to 0." (You could keep using it as an artificial limit to ensure maximum columns returned is lower than 255).


To my first point again, I believe some CQuery objects that run use and utilize multiple sql statements -- so the PrepareFetch may have to resize the allocation multiple times in relation to that which would introduce possible memory fragmentation due to having to resize the vector more than once.

You could write a custom container to store some of the information on the stack or something similar to avoid pointer dereferencing and heap allocations for a little bit. E.g: SmallQuery or something similar. I like using stack allocated space for smaller based queries as it'd be faster, and it'd skip having to dynamically allocate that memory.

I brought up MAXCOL earlier because Flyff doesn't use up to it or not even close to it. Increasing the allocation of those char pointers for the inventory isn't necessary at all, you could just utilize more columns. This also keeps it working with older odbc settings where VARCHAR MAX doesn't bind properly to the variables. Just going back to the non 168 inventory version will drastically decrease memory allocation. (Bonus, flyff doesnt do anything with blobs, so no need to write a blob reader either).

Then another thing that would be nice is using another struct or something to separate lCol, Col and ColName. lCol either being strlen length or an indicator for the fetch statement. I only bring that up because of so many similar names.

There’s a lot you could change or rewrite, but I’ve sent code that will work with almost any data source and give you an edge. The vectors will grow only up to a certain size (no larger than SQLSMALLINT), because that’s what the default source version limits them to.


This CQuery is pretty awful by itself, but it’s the fastest and most practical solution. If you want to make tweaks, I’m all for it. Feel free to send any lengthy texts or quotes from MSDN or other sites.;)
 
There’s a lot you could change or rewrite, but I’ve sent code that will work with almost any data source and give you an edge. The vectors will grow only up to a certain size (no larger than SQLSMALLINT), because that’s what the default source version limits them to.

This CQuery is pretty awful by itself, but it’s the fastest and most practical solution. If you want to make tweaks, I’m all for it. Feel free to send any lengthy texts or quotes from MSDN or other sites.;)

If my previous reply came across a bit blunt or overloaded, that wasn’t my intention. I mostly wanted to lay out ideas and considerations for anyone else exploring changes to CQuery and inspire conversation. Some of the points might've come off as nitpicks (like the MAXCOL check), but they were more aimed at helping future readers understand.

You're right: once you drop the MAXCOL static array and go fully dynamic with the column vector, bounds checking like MAXCOL becomes obsolete. I only mentioned it for completeness and clarity, since some devs might still use it as a soft limit, safety measure for having too many columns, or debugging purposes.

As for layout tweaks like separating lCol, Col, and ColName into a struct, those are more about readability or potential structural alignment improvements than major performance wins, so it's still a bit of a nitpick.

On the topic of memory layout and fragmentation, it's very true that it's priority for many projects today. But I still think we should strive for efficient designs, even when the performance gain might be marginal. Otherwise, the software ecosystem slowly drifts toward “heavier by default” apps that demand newer hardware for tasks they used to handle fine. You see that a lot with poor SIMD usage or inefficient cache access patterns (like strided matrix iterations, for example).

Of all the ideas, the one about using multiple columns for the inventory is probably the best and quickest next to the one you've provided. Reducing each buffer allocation from 51,000 bytes back to 8192 bytes is far more efficient. It seems like that high buffer size was anticipating worst-case string lengths, but in practice, values like GetAbilityOption() barely use more than a byte—certainly not the full 10+ chars that a long integer string representation might require.

On the idea of something like a SmallCQuery, I was drawing a parallel to Boost::SmallVector. It’s a good solution for small datasets because it allocates on the stack up to N, and only moves to the heap when needed—avoiding branches that check where data is stored, and benefiting from better cache behavior (at least for the stack-resident case). That said, there's always a trade-off—SmallVector keeps extra N * sizeof(T) space in the object, and if sizeof(T) is something like 51,000, it quickly becomes unusable on the stack. At that point, you’re back to relying on heap access, and cache-wise, you’re not saving much. With 8192-byte elements, a 64-byte cache line means you’re jumping lines roughly 128 times just to walk the full buffer, more if it’s not perfectly aligned. Prefetching helps a bit, but only so far.

For memory fragmentation: a custom thread-safe allocator or app-wide thread-safe memory pool could absolutely help. Especially if paired with lightweight GC. In CQuery’s case, the allocation patterns are mostly predictable—query begins, results fetched, query cleared, but sometimes reused or re-prepared in place. Even something like a slab or arena allocator scoped to a query's lifetime could make a difference without adding much complexity. And a lightweight GC can keep memory usage lower during non-peak hours.
 
If my previous reply came across a bit blunt or overloaded, that wasn’t my intention. I mostly wanted to lay out ideas and considerations for anyone else exploring changes to CQuery and inspire conversation. Some of the points might've come off as nitpicks (like the MAXCOL check), but they were more aimed at helping future readers understand.

You're right: once you drop the MAXCOL static array and go fully dynamic with the column vector, bounds checking like MAXCOL becomes obsolete. I only mentioned it for completeness and clarity, since some devs might still use it as a soft limit, safety measure for having too many columns, or debugging purposes.

As for layout tweaks like separating lCol, Col, and ColName into a struct, those are more about readability or potential structural alignment improvements than major performance wins, so it's still a bit of a nitpick.

On the topic of memory layout and fragmentation, it's very true that it's priority for many projects today. But I still think we should strive for efficient designs, even when the performance gain might be marginal. Otherwise, the software ecosystem slowly drifts toward “heavier by default” apps that demand newer hardware for tasks they used to handle fine. You see that a lot with poor SIMD usage or inefficient cache access patterns (like strided matrix iterations, for example).

Of all the ideas, the one about using multiple columns for the inventory is probably the best and quickest next to the one you've provided. Reducing each buffer allocation from 51,000 bytes back to 8192 bytes is far more efficient. It seems like that high buffer size was anticipating worst-case string lengths, but in practice, values like GetAbilityOption() barely use more than a byte—certainly not the full 10+ chars that a long integer string representation might require.

On the idea of something like a SmallCQuery, I was drawing a parallel to Boost::SmallVector. It’s a good solution for small datasets because it allocates on the stack up to N, and only moves to the heap when needed—avoiding branches that check where data is stored, and benefiting from better cache behavior (at least for the stack-resident case). That said, there's always a trade-off—SmallVector keeps extra N * sizeof(T) space in the object, and if sizeof(T) is something like 51,000, it quickly becomes unusable on the stack. At that point, you’re back to relying on heap access, and cache-wise, you’re not saving much. With 8192-byte elements, a 64-byte cache line means you’re jumping lines roughly 128 times just to walk the full buffer, more if it’s not perfectly aligned. Prefetching helps a bit, but only so far.

For memory fragmentation: a custom thread-safe allocator or app-wide thread-safe memory pool could absolutely help. Especially if paired with lightweight GC. In CQuery’s case, the allocation patterns are mostly predictable—query begins, results fetched, query cleared, but sometimes reused or re-prepared in place. Even something like a slab or arena allocator scoped to a query's lifetime could make a difference without adding much complexity. And a lightweight GC can keep memory usage lower during non-peak hours.
I agree with you, but no one’s going to try to completely rewrite CQuery, because that would mean rewriting all of the DB files (over 130 such classes are instantiated when dbsrvr.exe starts up) I’ve already verified that. It makes sense in theory, but:

  1. It would take too much time
  2. It would introduce new bugs
  3. The default code worked even on older PCs and ran quite fast

As for tabs in the inventory - that is certainly a more efficient solution, and I fully agree, but since 99% of admins use exactly 168 slots, I optimized specifically for that case, and the 51k buffer size wasn’t my decision but part of the 168-slot system (I just modified what was already there).


Moreover, since CQuery is used heavily in the engine and at least three instances of that class live for the entire lifetime of dbsrv.exe, changing the code presents additional challenges.


This is a simple, memory-focused fix rather than a speed optimization. Performance will be slightly lower here (due to dynamic arrays), but the impact is minimal, making it a straightforward solution (especially important for the x86 executable, which has a RAM limit).
 
Back