开发者

is it faster to reference a textbox's text property for a test or assign a string to the property then test?

开发者 https://www.devze.com 2023-03-20 18:41 出处:网络
I\'ve been wondering which is faster (or if it even makes a difference), referencing a textbox\'s Text property or a string assigned to that value?

I've been wondering which is faster (or if it even makes a difference), referencing a textbox's Text property or a string assigned to that value? Ref textbox.Text

if(textbox1.Text == "A")
{ //do a million iterations
}

Or

string aString = text开发者_运维百科box1.Text;
if(aString == "A")
{ //do a million iterations
}


I made just a quick analyze using stop watch: 10.000.000 iterations.

In first case it returns to me: 00:00:21.56

In second case it returns to me: 00:00:42.62

In second case you have Get accessor + new pointer to string every iteration, so its slower.

Hope this helps.

EDIT

I put all code of any case inside the iteration. Seems that is the quetion.


I don't think it will make any difference if compiler optimisation is on, but you could test this. Simply repeat the code a couple of million times with a StopWatch class to measure the timing of the total operation.


I think the second option is faster. Reading the property is executing a function which reads the value of the textbox. There is a chance it gets optimized away, on the other hand there may be also a chance the value changes while the loop is executing so it needs to check it every time the property is read.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号