I have two methods that are essentially the same, except for one subtraction operation. The one including subtraction is over 100 times slower than the one without it. This makes no sense to me.
The methods take an array of Booleans and turn it into a MemoryBlock where each bit (not byte) represents true/false.
Here’s the “slow” one:
[code]Protected Function EncodedBytesStringFromPoints(Points() As Boolean) as String
dim ms as double = Microseconds
if Points() = Nil or Points.Ubound = -1 then return “”
#pragma DisableBackgroundTasks
’ express a boolean array as bits in a memoryblock
dim j, k, bytePos, size, bitPos, value as integer
’ This is how many bytes we need
size = ceil( (Points.Ubound+1) / 8 )
’ make the memoryblock
dim mb as new memoryblock( size )
size = size - 1
’ write bits
for j = Points.Ubound DownTo 0
if Points(j) then
k = Points.Ubound - j // *** this line makes the operation over 100 times slower ???
bytePos = size-floor(k / 8)
bitPos = k mod 8
value = pow( 2, bitPos )
mb.byte( bytePos ) = Bitwise.BitOr( mb.byte( bytePos ), value )
end if
next
System.DebugLog str( Microseconds - ms )
return mb
End Function
[/code]
And here’s the “fast” one. The only difference is that the order of the bits is reversed.
[code]Protected Function EncodedInvertedBytesStringFromPoints(Points() As Boolean) as String
dim ms as double = Microseconds
if Points() = Nil or Points.Ubound = -1 then return “”
#pragma DisableBackgroundTasks
’ express a boolean array as bits in a memoryblock
dim k, bytePos, size, bitPos, value as integer
’ This is how many bytes we need
size = ceil( (Points.Ubound+1) / 8 )
’ make the memoryblock
dim mb as new memoryblock( size )
size = size - 1
’ write bits
for k = Points.Ubound DownTo 0
if Points(k) then
bytePos = size-floor(k / 8)
bitPos = k mod 8
value = pow( 2, bitPos )
mb.byte( bytePos ) = Bitwise.BitOr( mb.byte( bytePos ), value )
end if
next
System.DebugLog str( Microseconds - ms )
return mb
End Function
[/code]
To perform the test:
Sub Open() Handles Open
dim a, b as string
dim points() as boolean = Array( true, false, false, false, true, false, true, true, false, false, true, false, false, true, true) // 100010110010011
a = EncodedBytesStringFromPoints( points() )
b = EncodedInvertedBytesStringFromPoints( points() )
quit
End Sub
I must be missing something?