Any reason to use MemAlloc

BlitzMax Forums/BlitzMax Programming/Any reason to use MemAlloc

N(Posted 2005) [#1]
Is there any reason why you should use MemAlloc when you can just create an array of bytes? You can read from and write to it the same way, you can create a bank from it, etc. -- so why use MemAlloc over a byte array? You even access them nearly the same way (you use [idx]).

Byte array
Local MyData:Byte[128]

Print MyData[idx]


MemAlloc
Local MyData:Byte Ptr = MemAlloc( 128 )

Print MyData[idx]


So, I'm wondering if there are any advantages to one or the other.

Advantages for MemAlloc:
- As far as I know, it's not controlled by the garbage collector, so you can pass it to an external library and it can free it later. With a Byte array, you would have to reference it somewhere to keep it in memory (or not call FlushMem, and not calling FlushMem would be a bad idea).
- Dereferencing it is fun.
Disadvantages:
- MemAlloc is an ugly function name.

Advantages of the Byte array:
- Controlled by the garbage collector.
Disadvantages:
- You can't dereference it for fun.

So, am I missing anything from those?


DStastny(Posted 2005) [#2]
Only thing I can think of is there might be some compiler overhead to the array that is not present with MemAlloc

Although that might be neglibile, I suspect internally the array has to call MemAlloc as well as do the refernce counting for the array.

I dont know for sure but logic tells me Memalloc is less code generated by the compiler.

Doug Stastny


Bot Builder(Posted 2005) [#3]
What about this:

Local MyByte:Byte Ptr=MemAlloc(128), MyInt:Int Ptr=MyByte

MyInt[0]=5006
Print MyByte[0]

Its a speedy memory playhouse... can you do this with arrays?


N(Posted 2005) [#4]
Local MyByte:Byte[128]
Local MyInt:Int Ptr = VarPtr MyByte[0]

MyInt[0] = 5006
Print MyByte[0]


I'd say you can, yes.


Bot Builder(Posted 2005) [#5]
Yes, well, that wasnt very fair.