6

Particularly: Is Marshal safer? Are pointers faster?

int pixel = Marshal.ReadInt32(bitmapData.Scan0, x * 4 + y * bitmapData.Stride);
int pixel = ((int*)bitmapData.Scan0)[x + y * bitmapData.Stride / 4];
Ansis Māliņš
  • 1,684
  • 15
  • 35

2 Answers2

1

There is no difference. If you look at the code from Marshal.ReadInt32 you will see it uses pointers to perform the same thing.

The only 'benefit' with Marshal is that you not have to explicitly allow unsafe code. IIRC, you also require FullTrust to run unsafe code, so that may be a consideration.

leppie
  • 115,091
  • 17
  • 196
  • 297
  • Just wanted to chime in and say that there is a performance difference, I believe it's due to function invocation. It's minuscule if you're not doing many marshalling calls, but for iterating over bitmaps it can be quite large. – ivanPfeff Oct 03 '18 at 17:58
0

I personally prefer using Marshal mostly because I shun unsafe code. As to which is faster, I'm not sure but I am certain that operating pixel by pixel is liable to be slow however you do it. Much better is to read an entire scanline into a C# array and work on that.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • Reading the scanline into an array would require a copy which could take much more space/memory/time. – leppie Jul 27 '11 at 11:58
  • @leppie Actually, reading a scanline into an array would result in a copy which would likely take less time than pixel by pixel copying. – David Heffernan Jul 27 '11 at 12:03
  • Who is copying pixels? Normally one would just operate on the value and discard it (or move to the next value). – leppie Jul 27 '11 at 12:05
  • @leppie It's being copied into `pixel` – David Heffernan Jul 27 '11 at 12:08
  • What's wrong with operating on the native array directly? Or: who says managed arrays are faster than native ones? – Ansis Māliņš Jul 27 '11 at 12:08
  • No, that is simply a local/stack variable. What happens with it cant be assumed. I agree if you want to do the whole image at once, then the array approach might be better. But again, it is anyone's guess what happens after the assignment. – leppie Jul 27 '11 at 12:20