2

What's the performance consequence using the 'With' keyword in vb.net instead of using reusing the instance name over and over?

3 Answers 3

6

Assuming that you're comparing it to a local variable reference, there is no difference whatsoever; both will emit the exact same IL. (At least in Release mode)

However, if you're comparing it to repeated invocations of a property or indexer, With will be a little bit faster, and if you're comparing it to repeated invocations of a method, it might be much faster. (The With keyword will create a local variable and assign it to the object that you With'd, so the method will only be called once instead of on every line)

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

3 Comments

+1. Although I'd say you should only worry about these performance differences if you've measured and found a serious performance bottleneck in a specific block of code that uses With. "Premature micro-optimization is the root of all evil"
@MarkJ I'm talking about a huge batch operation (1000000+) entries
I didn't know you could use With with a method. Cool!
1

There is no runtime performance cost. It is just "syntactic sugar" to make your code look prettier.

1 Comment

It's not just "syntactic sugar", but it depends on what you're using at the time, see the answer by @Slaks.
0
sub xyz (ByRef param as MyObj)

'Local ref, same as with

dim o2 as YourObject = param.YourObject

o2.callSomething()


'Bad performance

param.YourObject.callSomething()

end sub

2 Comments

Please also provide some explanation to your answer as to how it answers the question.
Actuall your example is wrong, in your example the param.YourObject.callSomething() is faster as there is no subsequent call to YourObject and therefore the setup of the variable o2 is only extra overhead (unless ofcourse the compiler optimizes it to the same as param.YourObject.callSomething(). But if you call another function on YourObject after using .callSomething(), then using the o2 local ref would be faster.

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.