Path: utzoo!utgpu!news-server.csri.toronto.edu!bonnie.concordia.ca!thunder.mcrcim.mcgill.edu!snorkelwacker.mit.edu!usc!elroy.jpl.nasa.gov!jpl-devvax!lwall From: lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) Newsgroups: comp.lang.perl Subject: Re: what should length(@array) do ? Message-ID: <10989@jpl-devvax.JPL.NASA.GOV> Date: 10 Jan 91 18:47:03 GMT References: <1991Jan10.063409.7185@iwarp.intel.com> Reply-To: lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) Organization: Jet Propulsion Laboratory, Pasadena, CA Lines: 53 In article <1991Jan10.063409.7185@iwarp.intel.com> merlyn@iwarp.intel.com (Randal L. Schwartz) writes: : If you think that obody is huge, try something like: : : body: { : @obody = ; : $obodylen = 0; : for (@obody) { : $obodylen += length; : } : } : : Yeah, actually, that's close to your solution. You could also do it : with a grep() (my formerly favorite operator, until I got tired of it : :-) as in: : : body: { : @obody = ; : $obodylen = 0; : grep($obodylen += length, @obody); : } : : which probably isn't any faster than the previous code. (Larry?) It's pretty much a dead heat. I ran both five times on /etc/termcap and got. Slurp + foreach: 2.3u 0.8s 0:10 29% 335+1119k 23+0io 30pf+0w 2.2u 0.6s 0:08 36% 220+1134k 22+0io 68pf+0w 2.4u 0.6s 0:06 44% 161+1128k 21+0io 5pf+0w 2.1u 0.8s 0:10 29% 163+1130k 23+0io 5pf+0w 2.3u 0.6s 0:06 43% 163+1164k 22+0io 5pf+0w Slurp + grep: 2.3u 0.7s 0:06 51% 164+1164k 23+0io 6pf+0w 2.2u 0.7s 0:05 57% 161+1118k 23+0io 6pf+0w 2.3u 0.7s 0:05 55% 160+1101k 21+0io 5pf+0w 2.2u 0.7s 0:06 44% 161+1162k 23+0io 5pf+0w 2.1u 0.8s 0:06 44% 160+1115k 23+0io 5pf+0w Now, just so you know what kind of overhead you pay for the slurp, here's the original solution that just iterates over the lines and accumulates lengths into a variable: 0.9u 0.2s 0:03 30% 206+134k 23+0io 63pf+0w 0.8u 0.1s 0:01 63% 157+137k 21+0io 5pf+0w 0.9u 0.2s 0:02 50% 159+139k 21+0io 5pf+0w 0.9u 0.1s 0:02 51% 156+138k 21+0io 5pf+0w 0.9u 0.1s 0:01 52% 157+139k 21+0io 5pf+0w Moral: don't slurp files if you don't need to. Larry