2

Being new to VB.NET, I would like to know which of the following is more efficient in nature (time-wise (which code runs faster), code-neatness-wise, etc. you may add your own reasons too)

Dim a, b, c, d As Integer
a = 1
b = 2
c = 3
d = 4

OR

Dim a As Integer = 1
Dim b As Integer = 2
Dim c As Integer = 3
Dim d As Integer = 4

I am mainly asking this because my code has way too many Dim statements & coming from a Python background, I have never ever seen soooo many declarations (I do need those though, trust me). Is this okay? Or am I coding in a bad style?

2
  • IF your code has "way too many Dim statements" then maybe a refactor should take place? Nothing worse than having a method with too much going on! Commented Nov 8, 2013 at 12:45
  • I really need those many variables. It's actually part of the refactoring! :D Commented Nov 8, 2013 at 12:48

3 Answers 3

6

Runtime performance will be identical, as they both compile to the same IL.

.locals init ([0] int32 a,
       [1] int32 b,
       [2] int32 c,
       [3] int32 d)
IL_0000:  ldc.i4.1
IL_0001:  stloc.0
IL_0002:  ldc.i4.2
IL_0003:  stloc.1
IL_0004:  ldc.i4.3
IL_0005:  stloc.2
IL_0006:  ldc.i4.4
IL_0007:  stloc.3
IL_0008:  ret

Style-wise, I would avoid declaring multiple variables on one line (as in your first example). One "concept" per line is easier to read - as you don't have to visually parse commas.

Sign up to request clarification or add additional context in comments.

Comments

6

For the sake of clarity, perhaps one variable per line with an assignment for me personally is easier to look at and much clearer.

I mean you can do this:

Dim a As Single = 1, b As Single = 2, x As Double = 5.5, y As Double = 7.5

Taken from here.

But things start to look a bit difficult at this point. It is entirely a prefernce thing I suppose!

2 Comments

Man, i have been using vb so long and i didn't knew that! The best answer by far.
Haha brilliant, haven't used VB for 4 years now!
-1

Both options are ok. Still if you are not happy then you can create an array as all variables are of the same data types. Hope that helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.