Skip to content

Commit

Permalink
Base64: Pre-allocate strings when encoding/decoding
Browse files Browse the repository at this point in the history
  • Loading branch information
garbear committed Oct 14, 2012
1 parent a2040c7 commit 4e02fe9
Showing 1 changed file with 3 additions and 0 deletions.
3 changes: 3 additions & 0 deletions xbmc/utils/Base64.cpp
Expand Up @@ -35,6 +35,7 @@ void Base64::Encode(const char* input, unsigned int length, std::string &output)

long l;
output.clear();
output.reserve(((length + 2) / 3) * 4);

for (unsigned int i = 0; i < length; i += 3)
{
Expand Down Expand Up @@ -98,6 +99,8 @@ void Base64::Decode(const char* input, unsigned int length, std::string &output)
}
}

output.reserve(length - ((length + 2) / 4));

for (unsigned int i = 0; i < length; i += 4)
{
l = ((((unsigned long) m_characters.find(input[i])) & 0x3F) << 18);
Expand Down

2 comments on commit 4e02fe9

@garbear
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The maths were from the for loops and can be verified by stepping different length inputs in, if that makes sense

@jmarshallnz
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Math looks fine from a general 6<->8 bit encoding (3/4).

I suspect more optimisation could come from taking the conditionals out of the loops (i.e. first loop running up to length - 2), plus the second routine should probably run backwards through the string to find the length. Ofcourse, only after careful profiling that it actually makes a difference, ideally on i386 and arm.

Please sign in to comment.