0
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.

Ian Mercer
  • 38,490
  • 8
  • 97
  • 133
Kevin
  • 1,940
  • 3
  • 24
  • 38

3 Answers3

1

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 ... Local variable assignment to avoid multiple casts and, in particular, the accepted answer.

Community
  • 1
  • 1
Ian Mercer
  • 38,490
  • 8
  • 97
  • 133
  • 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 Apr 24 '10 at 03:24
  • It will cause no harm in an inner scope like this. I added another link which is relevant. – Ian Mercer Apr 24 '10 at 03:30
1

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 蒋晟
  • 15,125
  • 2
  • 28
  • 46
  • I have validators in place. I guess this was more of a theory based question. Not specific to a scenario. – Kevin Apr 24 '10 at 03:31
0

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

i_am_jorf
  • 53,608
  • 15
  • 131
  • 222