2

I am retrieving a byte blob from an SQLite database/record set. I am not experienced with garbage collection yet.

When I say:

Dim bt() As Byte
bt = r.fields("mybyteblob").value

... is that okay or unsafe?

I would like to make a copy of the byte array in the record set field, and I am not sure if I am simply referencing the byte array here instead of copying it.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
tmighty
  • 10,734
  • 21
  • 104
  • 218

2 Answers2

3

In your code you are only referencing the byte array.
If you want to copy it you need

Dim bt() As Byte 
if r.fields("mybyteblob").Value Is not Nothing then 
    dim lenArray = r.fields("mybyteblob").Length
    bt = new Byte(lenArray)
    Array.Copy(r.fields("mybyteblob").value, bt, lenArray)
end if

There is another alternative.
The Buffer class is faster than Array and more appropriate because you are using a byte array

Dim bt() As Byte 
if r.fields("mybyteblob").Value Is not Nothing then 
    dim lenArray = r.fields("mybyteblob").Length
    bt = new Byte(lenArray)
    Buffer.BlockCopy(r.fields("mybyteblob").value, 0, bt, 0, lenArray)
end if

Here a good question on the two methods

Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286
  • Thank you! But if I convert the byte array into an image right away, I would not have to CopyArray it, right? I mean if the byte array then gets garbage collected, my image will not be corrupted. Is that correct? – tmighty Oct 19 '12 at 07:57
  • 1
    Yes, you need to use a memorystream to pass the bytes to the stream and build an image from that stream. Then your original byte array is fred by the garbage collector – Steve Oct 19 '12 at 08:10
0

It is very unusual to run into garbage collection problems if you only write managed code (i.e. no P/Invoke).

Many smart people has put a lot of effort into making garbage collection work without you having to worry about it, so do just that: don't worry about it. Just write your code, and if you run into a specific behavior you don't understand, then ask about that particular behavior (and I can assure you that in 99.9967% [1] of the cases it will not be the garbage collector).

[1] This is not a random number. I've ran into a garbage collection gotcha once in ~10 years of programming. Assuming 10 bugs a day and 300 days of work per year, that makes 29999/30000 bugs which are not garbage-collection related = 99.9967%.

Rolf Bjarne Kvinge
  • 19,253
  • 2
  • 42
  • 86