Bottleneck in Base Conversion Function

I have a program I'm working on right now which uses a base conversion function to convert an integer to a text string. As far as I know, the solution I've come up with is a fairly textbook method of converting to another base, and it works.

The only problem is that this function I've written has some sort of bottleneck in it that is taking up a large amount of my resources. When profiling, I found that this function alone was responsible for nearly 50% of the timer samples taken.

My application also has an MD4 hashing algorithm in it. The hashing should be using a lot more resources than the base conversion, but the base conversion function is using more than double the resources of the hashing function. Anyone care to give me an idea of what exactly I'm doing wrong here?

1
2
3
4
5
6
7
8
9
10
11
void integerToKey(unsigned long long* location, std::string* output)
{
	unsigned long long num = *location;
	*output = "";

	while(num > 0)
	{
		*output += charset[num % (charsetLength + 1)];
		num /= (charsetLength + 1);
	}
}


In this context, "charset" is a char pointer containing a string of characters that represent the base I'm converting to. The variable "charsetLength" is merely an integer which holds the length of the character set, and is the base which the function will convert to.

Thanks for any help you offer.
The only thing I can think of is that operator+= on a std::string is fairly expensive unless you reserve the right amount of space beforehand.

You might consider output->reserve( 20 ); before your while loop.

(And BTW, why are you taking both parameters by pointer? The first one should be by value, and
the second one should be the return type of the function or else a reference).

Is 'charset' a map, by any chance? That would be a huge slowdown.
Charset is defined like so:

charset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

What other way can it be done?
In that case, yeah, I agree with jsmith.
Change line 4 to this:
1
2
output->clear(); //faster than assigning an empty C string
output->reserve(/*(a reasonable number)*/); //you can predict the exact size with log(num)/log(charsetLength+1)+1 
Topic archived. No new replies allowed.