Reputation: 4142
I have webpage where there is textbox with some default value. I have to clear that value from the textbox. I have two options:
textbox.text="";
or
textbox.text.remove(0,length);
Which one should I use? Does it make any impact on page performance (there are many textboxes placed on my page)?
Upvotes: 8
Views: 61292
Reputation: 43207
The best way to do this is
textbox.text = string.Empty;
Also remember that string type is immutable!
Upvotes: 28
Reputation: 11
textbox.text="";
or
foreach (var item in Page.Controls)
{
if (item is TextBox)
{
((TextBox)item).Text = "";
}
}
Upvotes: 1
Reputation: 161773
TextBox.Text = String.Empty;
is a lot more readable. It clearly states what you're trying to do: "set the text property of this text box to an empty string".I recommend you go with the assignment, as it is both faster, and much more clear.
Upvotes: 3
Reputation: 1106
The impact on performance will be minimal even with hundreds/thousands of calls, however
textbox.text = "";
should in theory be very slightly quicker, since you're just assigning a new value rather than processing the string (as .Remove does)
The best way to do this would be to do
textbox.text = String.Empty;
Update: if you're counting clock-cycles, String.Empty will actually execute faster as well, because it doesn't create a new object, whereas "" will create a new String object.
However, you should really not be too concerned about this, there aren't many ways to set a string to empty that will cause performance issues! You should use whichever is the most readable...
Upvotes: 0
Reputation: 23935
Presumably, you mean clear the value with javascript when a user clicks int the box? If so, it won't make any difference to performance.
I use jQuery in most pages, so I just hook up this function to clear default values onClick, using the ClientId of the textbox:
$('#ctl00_TextBox').click(function() { $('#ctl00_TextBox').val('');
If you mean clear it in codebehind use this:
yourTextBox.Text = String.Empty;
Upvotes: 1
Reputation: 144112
It makes no difference - do what is most readable for you and your colleagues.
Many prefer to use string.Empty
.
Upvotes: 9