views:

62

answers:

4
sqlInsertFrame.Parameters.AddWithValue("@UserName", txtUserName.txt);

Given the code above...if I don't have any need to move the textbox data into a string variable, is it best to read the data directly from the control?

In terms of performance, it would seem smartest to not create any unnecessary variables which use up memory if its not needed. Or is this a situation where its technically true but doesn't yield any real world results due to the size of the data in question.

Forgive me, I know this is a very basic question.

A: 

Never cache what you can compute. Your reasoning is sound.

jeffamaphone
+1  A: 

Actually it's not a very basic question at all. As far as performance goes it's hard to say without measuring. In this case, a local variable in an inner scope may well get optimized completely out of the picture by a smart compiler. It may exist only in the CPU registers.

Introducing a local variable can make your code much more readable, if it does, do it!

See also ... http://stackoverflow.com/questions/1438158/local-variable-assignment-to-avoid-multiple-casts and, in particular, the accepted answer.

Hightechrider
And thats what I'd normally do. For readability, I'd move it into a variable, but as I was working, it suddenly struck me that it might be useless, or even harm the application (short of readability)
Kevin
It will cause no harm in an inner scope like this. I added another link which is relevant.
Hightechrider
+1  A: 

No validation? Usually I cache the string and pass it to the business layer for validation, if the validation succeeds, then I save the cached string to the database. It is slower to get the string again from the Window than read the value off my cache.

Sheng Jiang 蒋晟
I have validators in place. I guess this was more of a theory based question. Not specific to a scenario.
Kevin
A: 

Also if you do this from a thread you're likely to get a cross thread operation exception.

Aaron Smith