XORing long strings opimization?

Alex Martelli aleax at aleax.it
Tue Nov 4 17:46:30 EST 2003


Peter Otten wrote:

> Noen wrote:
> 
>> Oh, didnt notice that as I wrote it. Thanks...
>> Anyway, this is how it should be.
>> 
>> def XOR(s1,s2):
>>      """ XOR string s1 with s2 """
>>      output = ""
>>      # Argument check
>>      if (type(s1) and type(s2)) != type(""):
>>          raise TypeError, "Arguments are not strings"
>>      if len(s1) != len(s2):
>>          raise ValueError, "Size differs in strings"
>>      # Xoring
>>      for i in range(len(s1)):
>>          output += chr(ord(s1[i]) ^ ord(s2[i]))
>>      return output
> 
> Oops, I missed one:
> 
>>>> xor2.XOR(1, "")
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "xor2.py", line 7, in XOR
>     if len(s1) != len(s2):
> TypeError: len() of unsized object

Checks apart -- on to optimization as per subject:

[alex at lancelot krb5module]$ timeit.py -c -s'from string import letters as S' 
'"".join([chr(ord(S[i])^ord(S[i])) for i in xrange(len(S))])'
10000 loops, best of 3: 113 usec per loop

i'm not sure i can do much better with strings.  arrays are cool, though:

[alex at lancelot krb5module]$ timeit.py -c -s'from string import letters as S'
-s'import array' 'x=array.array("b",S)' 'for i,v in enumerate(x): x[i]^=v'
'x.tostring()'
10000 loops, best of 3: 57 usec per loop

Morale: when you find yourself fiddling with lots of chr and ord, and care
about performance, think about "array('b', ... -- it could buy you an easy
speedup by a factor of 2, like here.


Alex








More information about the Python-list mailing list