From: Kristof Bastiaensen Date: 2007-01-30T02:05:11+09:00 Subject: Re: "a string".xor("another string") On Mon, 29 Jan 2007 15:08:08 +0000, Ken Bloom wrote: > once again, the result wasn't any faster. If you want fast, your best bet > is probably to write it in C. Or use an existing C extension :) Using NArray: require 'narray' require 'benchmark' class String def xor1(other) if other.empty? self else a1 = self.unpack("c*") a2 = other.unpack("c*") a2 *= 2 while a2.length < a1.length a1.zip(a2).collect{|c1,c2| c1^c2}.pack("c*") end end def xor2(other) if other.empty? self else if other.length < self.length div, mod = self.length.divmod(other.length) other = other * div + other[0, mod] end a1 = NArray.to_na(self, "byte") a2 = NArray.to_na(other, "byte") (a1 ^ a2).to_s end end end $a1 = "abcdefg" * 1000 $a2 = "hijkl" * 1000 Benchmark.bm do |x| x.report("xor1:") {$a1.xor1($a2)} x.report("xor2:") {$a1.xor2($a2)} end user system total real xor1: 0.030000 0.000000 0.030000 ( 0.029777) xor2: 0.000000 0.000000 0.000000 ( 0.000427)