Nothing to see here

Nothing to see here header image 2

arrMyData(5,5) <> arrMyData(5)(5)

February 12th, 2008 · 1 Comment

After wasting lots of time on trial and error, I decided to find out what the low-level difference was between vbscript arrays addressed as (x,y) and (x)(y).  Eric Lippert explained it better than I can, so just read his explanation.  If you want some code to demonstrate how things work, download my 2D array test.  It has a lot of in-line comments and should give you an idea of when you should use (x)(y) and when you should use (x,y).

(x)(y):
Use when you want to ReDim x and preserve the array contents.
Use when you want a sparse (or ragged) array.
Use for large 2D arrays that will be mostly empty.
(x,y):
Use when you don’t need to ReDim x.
Use for small 2D arrays that are created rectangular and have a structure that won’t change.
Use for large 2D arrays that will be fully populated with data.
Things to watch out for:

Dim array1(1,1)
array1(1,0) = split("hello world"," ",-1,1)

Using the code above, “hello” is actually stored in array(1,0)(0), not array1(1,0).  array1(1,0) actually contains a 2 element array!  The way to get around this is use a temp array to store the output of the split function, then a for loop to copy data from the temp array into array1.
If you have a pre-defined set of data you want to collect (ex: computername,userid,timestamp,eventtype), then an array of objects may be easier to use, and easier to understand if someone else wants to read your code.  A small example of an array of objects that took the place of  a 2D array for a recent project:

Class AuditEvent
	Public ComputerName
	Public Username
	Public Timestamp
	Public EventType
End Class
Dim objAuditEvent()
ReDim objAuditEvent(20)
for i=0 to ubound(objAuditEvent)
	Set objAuditEvent(i) = New AuditEvent
next
objAuditEvent(1).ComputerName = "L210C99"
objAuditEvent(1).Username = "user"
objAuditEvent(1).Timestamp = "02/11/2008 12:00:17"
objAuditEvent(1).EventType = "Logon"
ReDim Preserve objAuditEvent(1)
wscript.echo objAuditEvent(1).ComputerName
'Clean up objects
for i=0 to ubound(objAuditEvent)
	Set objAuditEvent(i) = Nothing
next

Tags: Computing

1 response so far ↓

Leave a Comment