In Visual Basic, is there a performance difference when using the IIf
function instead of the If
statement?
相关问题
- 'System.Threading.ThreadAbortException' in
- how to use special characters like '<'
- C# to VB - How do I convert this anonymous method
- Scaling image for printing
- if/else statement for defining a distribution in J
相关文章
- vb.net 关于xps文件操作问题
- Checking for DBNull throws a StrongTypingException
- Using the typical get set properties in C#… with p
- js if any value in array is under or over value
- BASH: Basic if then and variable assignment
- Bash script that creates a directory structure
- Load a .NET assembly from the application's re
- C# equivalent of VB DLL function declaration (Inte
...as to why it can take as long as 6x, quoth the wiki:
Essentially IIf is the equivalent of a ternary operator in C++/C#, so it gives you some nice 1 line if/else type statements if you'd like it to. You can also give it a function to evaluate if you desire.
Also, another big issue with the IIf is that it will actually call any functions that are in the arguments [1], so if you have a situation like the following:
It will actually throw an exception, which is not how most people think the function works the first time that they see it. This can also lead to some very hard to fix bugs in an application as well.
[1] IIf Function - http://msdn.microsoft.com/en-us/library/27ydhh0d(VS.71).aspx
I believe that the main difference between If and IIf is:
If(test [boolean], statement1, statement2) it means that according to the test value either satement1 or statement2 will executed (just one statement will execute)
Dim obj = IIF(test [boolean] , statement1, statement2) it means that the both statements will execute but according to test value one of them will return a value to (obj).
so if one of the statements will throw an exception it will throw it in (IIf) anyway but in (If) it will throw it just in case the condition will return its value.
VB has the following
If
statement which the question refers to, I think:The first is basically C#'s ternary conditional operator and the second is its coalesce operator (return
result
unless it’sNothing
, in which case return"Alternative"
).If
has thus replacedIIf
and the latter is obsolete.Like in C#, VB's conditional
If
operator short-circuits, so you can now safely write the following, which is not possible using theIIf
function:According to this guy, IIf can take up to 6x as long as If/Then. YMMV.
Better use If instead of IIf to use the type inference mechanism correctly (Option Infer On)
In this example, Keywords is recognized as a string when I use If :
Otherwise, it is recognized as an Object :