Forum Moderators: coopster & phranque

Message Too Old, No Replies

Perl Scalar Array Total Size in Bytes?

         

Brett_Tabke

5:35 am on Feb 8, 2002 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



What is the easiest and most speed and resources friendly way to determine the total size in bytes of all elements of a scalar array?

The following is what I want to do, but this isn't how I want to do it because it is incredibly slow. Seems like there should be an easier (faster) way:

[perl]
for (@foo) {
$total+=length($_);
}
[/perl]

Air

8:20 am on Feb 8, 2002 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member




$size = "@foo";
$howbig = length $size;

littleman

8:28 am on Feb 8, 2002 (gmt 0)



Slick! Funny how you don't see the simple approaches sometimes.

Brett_Tabke

8:52 am on Feb 8, 2002 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



I was staying away from that one because it dupes the array. I'm into an array that can be potentially mutimegabyte. OH! But does make the light bulb go off looking at it:

$howbig = length("@foo");

Thanks.

btherl

8:44 am on Feb 13, 2002 (gmt 0)

10+ Year Member



The algorithm you gave at first looks like the most efficient.. finding string length takes time linear in the length of the string, and that's what you're doing :)

Maybe you can count the length of the array as you construct it? Or if it comes from an external source, get that source to do it for you. In C programming it's common to pass the length of a string as well as the string itself, to save having to find the length later on.

gethan

10:21 am on Feb 13, 2002 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



(Probably a little late .... but)

There's a bug in the $size=length("@array") also... you get a whole load of padding counted.

[perl]
#!perl

@array = ("Hello","Frogs","Toads","And","other","Amphibians");
for (@array) {
$size += length($_);
}

print "V1 - $size\n";

$size = length("@array");
print "V2 - $size\n";

$size = length("@array") - $#array;
print "V3 - $size\n";
[/perl]

$ ./test.pl
V1 - 33
V2 - 38
V3 - 33

Brett_Tabke

10:53 am on Feb 13, 2002 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



Thank you. Thank you.

It was a noncritical routine anyway. I just needed to know if I was dealing with a 100 bytes or a couple meg.