home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!cs.utexas.edu!sun-barr!ames!elroy.jpl.nasa.gov!usc!news!netlabs!lwall
- From: lwall@netlabs.com (Larry Wall)
- Newsgroups: comp.lang.perl
- Subject: Re: randomize.c
- Message-ID: <1992Sep1.210332.26149@netlabs.com>
- Date: 1 Sep 92 21:03:32 GMT
- References: <Bts28y.DJA@rahul.net> <AAS.92Aug31133620@rosmer.nr.no> <1992Aug31.183903.4143@cirrus.com>
- Sender: news@netlabs.com
- Organization: NetLabs, Inc.
- Lines: 36
- Nntp-Posting-Host: scalpel.netlabs.com
-
- In article <1992Aug31.183903.4143@cirrus.com> dhesi@cirrus.com (Rahul Dhesi) writes:
- : In <AAS.92Aug31133620@rosmer.nr.no> aas@rosmer.nr.no (Gisle Aas) writes:
- :
- : >Why not: perl -e '@l=<>;print splice(@l,rand($#l),1) while @l'
-
- A rand() returns a number *exclusive* of its endpoint, so you'd really want
-
- perl -e 'srand; @l=<>; print splice(@l, rand @l, 1) while @l'
-
- : I considered using splice and decided not to take the risk of a
- : possibly inefficient implementation. Later I was told that the perl
- : book already has such a program.
-
- Unless you know how things are implemented, it's best to try it both
- ways and see which is faster. Most builtins are fairly efficient,
- though you can occasionally beat them if you have a problem that's
- weird in some way. This one's weird enough that you might be able
- to beat splice by copying the actual strings like you did. As it happens,
- on a sparc the splice wins by about 20%.
-
- In general, you can assume that I haven't been totally stupid. :-)
-
- : Just how efficient is splice? I guess it depends on whether arrays in
- : perl are internally implemented as linked lists.
-
- Arrays are *not* implemented as linked lists. That would be tragic.
- It would force all subscripting operations (including splice) to be O(n).
- Yech.
-
- Arrays are implemented in C as an array of pointers to scalar headers
- which in turn point to the actual values. Splice merely needs to copy
- some number of pointers to fill the hole. It figures out whether to
- copy up from the front or down from the back. It's true that that's
- also O(n), or maybe O(n/2) or so, but machines are often optimized to
- move blocks of memory quickly, and a splice on the middle of an array
- is fairly rare as operations go. Subscripting, however, happens
- constantly, so we optimize for that.
-
- Larry
-