int(rand() + 1), int(rand()) +1, and hashes

C. Abney cabney at
Sun Jul 16 10:08:35 CDT 2000

On Sun, 16 Jul 2000, Russ Schnapp wrote:

> Okay, I'll bite.  Here are the code samples again:
> > sub randint1 {
> >         $r1 = int( rand(4) + 1 );
> >         $h1{$r1}++;
> > }
> > 
> > sub randint2 {
> >         $r2 = int( rand(4) ) + 1;
> >         $h2{$r2}++;
> > }
> randint2() ran slower than randing1(), and you're saying that's 
> because $r2 was a float while $r1 was an int?  I need to understand 
> this.  How did adding an integer (1) to the result of an int() generate 
> a floating result?

oh my, Eugene seems to've missed something in my post. $r1 and $r2 are
both ints.  It is in the assignment operation for each that the output
of rand() is converted from float to int.  This happens /before/ it's
used as a hash key, of course.  In one example it happens before adding
1, in the other example it happens after.  That's the only difference
other than speed.

Things are only getting muddier.  Both randint1 and randint2 use the
hash, and the hash index has been converted from an int in both cases.

But, in one case, rand() output was truncated to int before integer
addition and assignment to $rx, whereas in the other it was added with
an int /before/ truncation.  The second case turns out to be much faster
when the resulting int is used as a hash index.  But it makes no difference
in speed when the resulting ints are used as an array index!

I want to get inside that anomaly and am hoping for some help... :)
Maybe it would help to review the benchmark again, comparing the 2x2
matrix of algorithms?

Mighty Mouse is a cartoon. Superman is a real guy. No way a cartoon could beat
up a real guy! -- Teddy                                               C. Abney


The posting address is: san-diego-pm-list at

List requests should be sent to: majordomo at

If you ever want to remove yourself from this mailing list,
you can send mail to <majordomo at> with the following
command in the body of your email message:

    unsubscribe san-diego-pm-list

If you ever need to get in contact with the owner of the list,
(if you have trouble unsubscribing, or have questions about the
list itself) send email to <owner-san-diego-pm-list at> .
This is the general rule for most mailing lists when you need
to contact a human.

More information about the San-Diego-pm mailing list