Napivo1972 Posted October 7, 2004 Posted October 7, 2004 I was wondering. Do I need to take care when replacing ands and ors? Can anyone give me an example where I better do not replace and and or? Quote
Administrators PlausiblyDamp Posted October 7, 2004 Administrators Posted October 7, 2004 Both AndAlso and OrElse (that sounds weird read out loud) give a performance benefit by only evaluating the minimum number of arguments. e.g. given the following 2 simple functions Private Function Test1() As Boolean MessageBox.Show("Test1") Return False End Function Private Function Test2() As Boolean MessageBox.Show("Test2") Return True End Function if called from an if statement like If Test1() And Test2() Then MessageBox.Show("Both true") End If you should get both the messageboxs from Test1 and Test2 displayed - despite the fact that because Test1 returns false the overall result can never be true. Changing the if statement to If Test1() AndAlso Test2() Then MessageBox.Show("Both true") End If you only get the first messagebox as it realises the result will always be false so there is no reason to even evalute the second condition. However if Test2 performed some required functionality then that would also be skipped - this is the only time you would need to avoid AndAlso; however I would personally class that as a bad coding style anyway - relying on side-effects like that to get required code to execute is hard to debug / maintain and gives no real benefit. Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
Napivo1972 Posted October 7, 2004 Author Posted October 7, 2004 Thank you for this enlightening explanation. I understand now. Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.