Var's strange behaviour

BlitzMax Forums/BlitzMax Programming/Var's strange behaviour

Dubious Drewski(Posted 2005) [#1]
Say I have a large chunk of data that I want to use in a
function repeatedly. If I pass it normally, the computer by
default creates a new copy of that data for the function to
work with. But if you use Var, it creates a pointer to
the data, right?

Well that's what I thought anyway. If you run this code
with and without Var written in the function declaration,
you'll notice that using Var is actually slower. How
can transfering a huge chunk of data be quicker than
transfering a measly pointer? What's going on here?

Strict
Local times = 40

Local avg:Float
Local arr[100,1000,1000]
For Local tt = 0 To times
	Local time = MilliSecs()
	For Local a = 0 To 500000
		frat(arr)
	Next
	Print MilliSecs()- time
	avg:+MilliSecs()- time
Next

Print
Print "Average time: "+avg/(times+1)


Function frat(arr[,,] Var)
	
End Function



Koriolis(Posted 2005) [#2]
If I pass it normally, the computer by
default creates a new copy of that data for the function to
work with
Nope, see below.
How
can transfering a huge chunk of data be quicker than
transfering a measly pointer?
Simple. An array is in BlitzMax an object in its own right. Objects are passed by reference, meaning that in your function you if you modify the passed array, it's really the global array you're modifying. It also means that under the hood a simple pointer is ppased (fast). When using 'Var' what changes is that it's the *reference to the array* that is now modifiable. In short you kinda get a reference to a reference. So under the hood a pointer to the pointer to the array is passed. Then, to access the array elements, a double indirection is needed (slower).

Now the thing is that you are not accessing the elements in 'frat', so the answer is harder. There could be not so obvious reasons. But in any case your initial assumption was wrong and there is no reason to use 'Var' here.


Grey Alien(Posted 2005) [#3]
double indirection, lol. I once started writing a shoot 'em up in DOS C++ using types but did a test and found plain old arrays were loads faster and did it like that in the end but it was a pig to maintain!


Dubious Drewski(Posted 2005) [#4]
Hmm, I see. That's good to know. So Var should only be
used with single variables, but never objects?


Koriolis(Posted 2005) [#5]
That's still no exactly that. It's just that given that objects (including arrays) are passed by reference anyway, there's no point using 'var' in the hope to improve efficiency. You use 'var' if you want to be able to modify the real variable passed as a parameter (and not a local copy). That's true for 'single variables' as you call them as well as objects (you may want to modify the original reference to the object, rahter than getting a local copy).
In short the only use of 'var' has to do with the program's logic rather than its efficiency.