Best way for stepping through rows

V

Vayse

I have a Datatable, dtCustomers. It has several fields. I need to loop
through it, passing only the Customer Code to another function. Function
name is CalcVat.
Does looping through rows have a memory overhead? As in, which is better:

Method A)
For each rowCustomer in dtCustomers.Rows
CalcVat(rowCustomer("CustCode")
Next

Method B)
Dim iLoop as Integer
For iLoop = 0 to dtCustomers.Rows.Count
CalcVat(iLoop).Item("CustCode")
Next

Normally, I use Method A, just want to know which is the most efficient.
Thanks
Vayse
 
D

David Browne

Vayse said:
I have a Datatable, dtCustomers. It has several fields. I need to loop
through it, passing only the Customer Code to another function. Function
name is CalcVat.
Does looping through rows have a memory overhead? As in, which is better:

Method A)
For each rowCustomer in dtCustomers.Rows
CalcVat(rowCustomer("CustCode")
Next

Method B)
Dim iLoop as Integer
For iLoop = 0 to dtCustomers.Rows.Count
CalcVat(iLoop).Item("CustCode")
Next

Normally, I use Method A, just want to know which is the most efficient.
Thanks


The most efficient pattern is to use the iterator and a DataColumn
reference.

Dim colCustomer as DataColumn = dtCustomers.Columns("CustCode")
For each rowCustomer in dtCustomers.Rows
CalcVat(rowCustomer(colCustomer)
Next

David
 
V

Vayse

Sorry, Method B should be:

Dim iLoop as Integer
For iLoop = 0 to dtCustomers.Rows.Count
CalcVat(dtCustomers.Rows(iLoop).Item("CustCode")
Next
 
C

Cor Ligthert [MVP]

Vayse,

Between those as you describe is the A the most efficient, but not always
possible.

The method David describes will (if you add that one ")" ) at the end,
inside both method gives probably more performance benefit. For both this is
only worthfull thinking about if you are doing endless times looping through
very huge tables.

(assuming that your method B goes until count-1)

I hope this gives an idea

Cor
 
K

Kevin Yu [MSFT]

Hi Vayse,

I agree to use foreach loop, since the compiler will optimize the loop
process.

Kevin Yu
Microsoft Online Community Support

============================================================================
==========================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
============================================================================
==========================

(This posting is provided "AS IS", with no warranties, and confers no
rights.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top