Performance suffering from frequent memory allocation

I was suffering from a bad performance problem of my project. Well, it took more than 3 days for a complete run, which made my customer really upset. People like me don’t care about performance too much during our design or implementation phase. I mean, at least not paying too much attention. I believe that performance should be considered only when it is really a problem. Well, I guess I need to take a good consideration for my project now.

After painfully gathering information from application logs (it took more than 7 days after enabling the debug message mode), I quickly spotted a few bottlenecks. All of them seem to be related to database query. “DBA job”, I thought. But then I found a strange case. Even if a specific action was done solely on cache, it was still very slow. Well, that was not what I expected (it was intended to be a cache!).

The cache is really a Java Vector object, and it is used for storing 60000+ entries. All the entries are fetched from database and sequentially added into the cache. Now you might know what the problem is. That’s right! The Vector object was created without specifying an initial capacity. As the cache grows, it is frequently reallocated and copied. The difference is huge: 10 seconds versus 7 hours. Really, I’m not bluffing.

I have similar experience with Java String concatenation. Using StringBuffer instead of String concatenate operator when concatenating large number of String objects could give you the same number of performance gain. I never knew the difference could be so dramatic until I encountered such cases.

Our code could be much slower than what we expected if we don’t pay at least some attention to it. Next time when I create a collection object, I’ll keep an eye on the initial capacity.

Close