question about declaring variables

BigJimSlade

Registered User.
Local time
Today, 10:12
Joined
Oct 11, 2000
Messages
173
Hi, Big Jim here:

Can anyone tell me the difference between these two pieces of code?

***********************
Dim rst as recordset
Set rst = currentdb.OpenRecordset("SELECT * FROM MyTable")
Label.Caption = rst!Field
***********************
Dim rst as Recordset
Dim strField as String
Set rst = currentdb.OpenRecordset("SELECT * FROM MyTable")
strField = rst!Field
Label.Caption = strField
***********************

I notice many programmers do the latter. Is there any reason as to why, and what would this be called? Does it effect performance?

Thanks in advance!

Big Jim
 
There's no "real" difference in outcome. Just seems like the 2nd version is declaring a variable that, if only used in the context presented, seems extraneous. I almost always go for brevity unless being more wordy will make the program function more obvious.
 
BigJimSlade said:
Can anyone tell me the difference between these two pieces of code?

Code:
Dim rst as recordset
Set rst = currentdb.OpenRecordset("SELECT * FROM MyTable")
Label.Caption = rst!Field
***********************
Dim rst as Recordset
Dim strField as String
Set rst = currentdb.OpenRecordset("SELECT * FROM MyTable")
strField = rst!Field
Label.Caption = strField

It's as dcx said, they do the exact same thing and the variable strField is unnecessary in the second example.

However, you may want to assign a value like that to a variable if you are going to use it repeatedly within the procedure/function. This means you are referencing a cache where the value is held rather than having to refernce the field object in the recrdset object each time.
 
Big Jim sends his many thanks to both of you!

Mile, I think that is what I was getting at. The variable is stored in cache while the reference to the object is not? So in the end, I guess storing the value in a variable, say looping through a bit of code 1,000 times, would speed things up.

Thanks again!

Big Jim
 
BigJimSlade said:
So in the end, I guess storing the value in a variable, say looping through a bit of code 1,000 times, would speed things up.

Yes. If the variable is going to be used more than once, and consecutively.
 

Users who are viewing this thread

Back
Top Bottom