Thursday, March 13, 2008

Integer Division in VB.NET

Copied this from http://www.devx.com/vb2themax/Tip/18244

It pretty much talks about the difference between doing division with the "/" vs "\"

Use integer division operator
Use "\" instead of "/" when performing divisions between Integers. The "/" operator returns a Single value, therefore the seemingly efficient line


C% = A% / B%
actually requires three implicit conversions, two for converting the operands from Integer to Single (to prepare them for the division) and one to convert the result from Single to Integer (to complete the assignment). If you use the "\" operator you don't incur in this overhead, and the division itself is faster. While we are on this topic, keep in mind that the "/" operator returns a Double value if at least one of its operands is a Double; therefore if you wish the highest precision when dividing two Integer or Single values, you should manually coerce one of them into Double type:

' this prints 0.3333333
Print 1 / 3
' this prints 0,333333333333333
Print 1 / 3#


No comments: