Skip to content
This repository
Browse code

Base64: Pre-allocate strings when encoding/decoding

  • Loading branch information...
commit 4e02fe92b80c9ef218d22d72d31be1338f5331b7 1 parent a2040c7
Garrett Brown authored October 14, 2012

Showing 1 changed file with 3 additions and 0 deletions. Show diff stats Hide diff stats

  1. 3  xbmc/utils/Base64.cpp
3  xbmc/utils/Base64.cpp
@@ -35,6 +35,7 @@ void Base64::Encode(const char* input, unsigned int length, std::string &output)
35 35
 
36 36
   long l;
37 37
   output.clear();
  38
+  output.reserve(((length + 2) / 3) * 4);
38 39
 
39 40
   for (unsigned int i = 0; i < length; i += 3)
40 41
   {
@@ -98,6 +99,8 @@ void Base64::Decode(const char* input, unsigned int length, std::string &output)
98 99
     }
99 100
   }
100 101
 
  102
+  output.reserve(length - ((length + 2) / 4));
  103
+
101 104
   for (unsigned int i = 0; i < length; i += 4)
102 105
   {
103 106
     l = ((((unsigned long) m_characters.find(input[i])) & 0x3F) << 18);

2 notes on commit 4e02fe9

Garrett Brown
Collaborator

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

jmarshallnz
Owner

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.
Something went wrong with that request. Please try again.