Page 1 of 1

Variables or repeated function calls?

Posted: Wed Jan 23, 2019 3:39 am
by RobertSF
Generally, you want to avoid repeated function calls. For example, if your string processing calls for repeatedly using the length of the string, you call Len(string) once, save the result in a variable, and then use the value in the variable instead of calling Len(string) over and over. This makes sense, especially if you're dealing with an complex object model in which you have to invoke methods five levels deep to get anything done.

But I was wondering if PureBasic is lean enough that the overhead of calling a function like GetCurrentDirectory() or GetGadgetText() is low enough that it's not worth it to create a variable and assign the result to it. I know some forum members are handy with a disassembler, so I guess they would know this. :)

Re: Variables or repeated function calls?

Posted: Wed Jan 23, 2019 3:57 am
by Mistrel
Only profiling will tell you if it's fast enough for your use case.

This is the same no matter what language you use. :wink:

Re: Variables or repeated function calls?

Posted: Wed Jan 23, 2019 5:41 am
by Dude
My rule is to never create a variable if it's only going to be used once.

Re: Variables or repeated function calls?

Posted: Thu Jan 24, 2019 4:31 am
by RobertSF
Dude wrote:My rule is to never create a variable if it's only going to be used once.
Excellent rule. But is the corollary "always create a variable if it's going to be used more than once" true?

For example, the function UserName(). It returns the logged in user name. It doesn't seem to involve much calculation. Would you...
Define CurrentUser.s = UserName()
... or instead just use UserName() wherever needed?

Re: Variables or repeated function calls?

Posted: Thu Jan 24, 2019 6:14 am
by Dude
Yes, it's faster and better to create a variable to repeatedly reference things like UserName() on a regular basis. There's a post proving it somewhere, and Fred confirmed it.