skip navigation links

The Internet's only wheelchair-accessible website.

blog

software/engineering

What is wrong with this method?

(December 19th, 2004 - 12:57PM)

I encountered a method like this in a Java project at work. Can you tell what's wrong with it?

String BuildStringFromKeys(KeyList keys)
{
    String workingString = "";
    for (int crntKey=0; crntKey<keys.Count(); crntKey++)
    {
        workingString += keys[crntKey];
    }
    return workingString;
}

Note that this isn't the exact method - I rewrote it from memory because the one in the code is obviously proprietary. And I haven't put this method through a compiler, so I'm not sure if it's actually valid. Just pretend it is. ;)

In any event, the problem with the above method is that it breaks down if the keys structure gets very large. This is because of this line:

workingString += keys[crntKey];

Many people probably don't pay attention to these things, but if the keys list contains a lot of values then workingString will start to get quite large. And every time you append to the string with the += operator, you may be forcing the Java Virtual Machine to reallocate memory for the string because it's larger.

The particular problem I encountered with the method above is that when enough keys were passed into the function, then workingString would get very large - around 600KB. With every iteration of the loop, the string would require even more memory as it was constantly growing. The process of reallocating that memory so many times jammed up the system.

In short, that simple function shown above was taking a long time to execute, because it was not efficiently dealing with string manipulation.

The above example goes to show how a few lines of code in Java can translate into something far larger and more problematic without the programmer realizing it.

So, the lesson of the day is:
Be wary of the memory management required for string manipulation.

permanent link - digg this post - 0 comments

0 comments

post comment

Required fields are marked with a *

mail@stevekwan.com