Hi all,
What would be the fastest way to get a random boolean?
Currently I use a random number and assign true or false depending on wether it is odd or even, but this seems like a crutch.
Anything more elegant?
TIA
Markus
Hi all,
What would be the fastest way to get a random boolean?
Currently I use a random number and assign true or false depending on wether it is odd or even, but this seems like a crutch.
Anything more elegant?
TIA
Markus
Off the top of my head
Function RandomBoolean() As Boolean
static r as new Random
return r.InRange( 0, 1 ) = 1
End Function
Nice. I always forget that you can return an equation.
Thanks Kem!
Fastest way would be avoiding instantiating an object (malloc + init). Ticks or millisecs and MOD to get odd or even.
If speed is not critical, Kem approach is not that fast, but quite elegant.
But he only instantiates it once and reuses it often.
You are right Tim! I did not notice the Static and read Dim. I’m getting older…
Ahhhhh, ok, I never thought about it.
When I often call a Function, with a folderitem for example, it’s better to use a Static than a Dim ?
[code]Static MyFldItem as FolderItem
MyFldItem = Nil ’ To be sure to don’t use the previous one[/code]
is better (quickest) than
Dim MyFldItem as FolderItem
Yes ?
No, if you are going to create a new one anyway, use Dim.
Static is just a quick way of leaving an object around that your plan to reuse. It’s exactly the same in effect as storing the object in a module’s property as every call to a method will get the same object (or variable), even if that method is in several different instances of a class.
For example, suppose you have defined this method in your class MyClass:
Function DoSomething()
static counter as integer
counter = counter + 1
return counter
End Function
Now consider this code:
dim a as new MyClass
dim b as new MyClass
dim c as new MyClass
dim cnt as integer
cnt = a.DoSomething()
cnt = b.DoSomething()
cnt = c.DoSomething()
// cnt is now 3
That is different than if counter had been a property of the class. In that case, cnt would have been 1 by the end.
So static has its uses, but you have to be careful that its an appropriate use. In your example, if you are going to be reusing the same FolderItem, then you’d use static, maybe something like this:
static f as FolderItem = SpecialFolder.Desktop.Child( "MyFolder" )
That initialization only happens once. If it’s a more complex object, then maybe you’d do something like this:
static rx as RegEx
if rx is nil then
rx = new RegEx
rx.SearchPattern = "some pattern"
rx.Options.CaseSensitive = True
end if
Thank you Kem.