Variables or repeated function calls?

Everything else that doesn't fall into one of the other PB categories.
RobertSF
User
User
Posts: 61
Joined: Thu May 03, 2018 4:24 pm

Variables or repeated function calls?

Post 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. :)
Mistrel
Addict
Addict
Posts: 3415
Joined: Sat Jun 30, 2007 8:04 pm

Re: Variables or repeated function calls?

Post 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:
Dude
Addict
Addict
Posts: 1907
Joined: Mon Feb 16, 2015 2:49 pm

Re: Variables or repeated function calls?

Post by Dude »

My rule is to never create a variable if it's only going to be used once.
RobertSF
User
User
Posts: 61
Joined: Thu May 03, 2018 4:24 pm

Re: Variables or repeated function calls?

Post 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?
Dude
Addict
Addict
Posts: 1907
Joined: Mon Feb 16, 2015 2:49 pm

Re: Variables or repeated function calls?

Post 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.
Post Reply