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?

有帮助吗?

解决方案

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.

其他提示

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!

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top