Empty Memoryblock?

Is there a quick way to determine if a memoryblock of a million bytes contains ONLY chrb(0) s?

One way, which seems to work, (hopefully it is comparing the contents not the address…)

 dim empt as new MemoryBlock(1000 * 1000)
 if empt <> theothermemoryblock then
end if

That allocates a memory block just for compare.
At least make it a static variable, so you only do it first time.

in MBS Plugin we have a function to check for all zero:
MemoryBlock.BytesZeroMBS(srcOfs as Integer, numBytes as Integer) as Boolean

Excellent. :slight_smile:
I was hoping you did, but I couldn’t find anything in the help

I did some testing using three techniques:

  • Create a new MemoryBlock and compare to original.
  • Store an empty MemoryBlock via Static and compare to original.
  • Iterate over the MemoryBlock using a Ptr.

I ran each method 5 times against an empty MemoryBlock, then 5 times against one where only the last byte was set to 1.

Using the Ptr technique was about 10 times faster than the others, about 0.75 ms vs. 7.5 ms (give or take).

Here is the function for your reference:

Public Function IsZero3(mb As MemoryBlock) As Boolean
  #if not DebugBuild
    #pragma BackgroundTasks false
    #pragma BoundsChecking false
    #pragma NilObjectChecking false
    #pragma StackOverflowChecking false
  if mb.Size = 0 then
    return true
  end if
  const kZero as UInt64 = 0
  var p as ptr = mb
  if mb.Size >= 8 then
    var lastInt64Index as integer = ( mb.Size - 8 ) \ 8 * 8
    var currentIndex as integer
    while currentIndex <= lastInt64Index
      if p.UInt64( currentIndex ) <> kZero then
        return false
      end if
      currentIndex = currentIndex + 8
  end if
  var lastIndex as integer = mb.Size - 1
  var firstIndex as integer = mb.Size - ( mb.Size mod 8 )
  for currentIndex as integer = firstIndex to lastIndex
    if p.Byte( currentIndex ) <> 0 then
      return false
    end if
  return true
End Function
1 Like

Surprisingly, that function is faster than the MBS function too. (4-5 ms for MBS).

Note that the test app was compiled using Aggressive.

Send me your test project and I can see what I can do.

1 Like

Don’t worry about me… I was only looking for something that didn’t do 1 million compares.

All the solutions provided here are easily fast enough for my needs.

Is a while loop faster than a for loop with a step of eight?

No measurable difference in my test.

Okay, in my test plugin was 42ms and now is 7ms.
Doing it in 64-bit chunks is faster and no idea why I didn’t do that last time.