I have a card game – written in Perl and with few objects, like this one:
package PlayingTable;
our (%Games, $Num);
sub new {
my $pkg = shift;
my $game = {
ID => ++$Num,
PHASE => WAITING,
KIBITZERS => [],
PLAYERS => [],
INFO => '',
RED5 => '',
TALON => [],
TABLE => {},
ROUND => 0,
PASS_ROUND => 0,
START => undef,
TURN => undef,
NPASSED => 0,
HOLDER => undef,
WHISTER1 => undef,
WHISTER2 => undef,
ACTIVE => undef,
PASSIVE => undef,
SHOW => undef,
BEFORE => undef,
SUIT1 => undef,
TRUMP => undef,
WINNER => undef,
};
$Games{$Num} = $game;
bless($game, $pkg);
}
and in the objects I have many hash and list references, which I often have to reset. For example, when a game round is over (one case: when all players passed), I will just call $player->{CARDS} = {}; to reduce the number of cards in the player hand to 0.
My question is if assigning [] and {} is a good enough practice or if it is too expensive, because the perl interpreter will malloc (or whatever it does to allocate memory) those new hash and array objects internally (will it really? or is the interpreter clever enough?).
I’m using (and do not want to upgrade) the stock CentOS perl package:
This is perl, v5.8.8 built for x86_64-linux-thread-multi
with CentOS 5.6 / 64 bit, on a 4GB machine and have max. simultaneous 500 players at evenings. My perl process (a non-forking daemon, polling TCP-sockets) uses right now:
top - 13:50:07 up 13 days, 3:25, 1 user, load average: 2.64, 3.36, 3.46
Tasks: 179 total, 2 running, 177 sleeping, 0 stopped, 0 zombie
Cpu0 : 3.6%us, 0.3%sy, 0.0%ni, 96.0%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Cpu1 : 6.0%us, 1.3%sy, 0.0%ni, 92.7%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Cpu2 : 13.7%us, 0.3%sy, 0.0%ni, 85.3%id, 0.7%wa, 0.0%hi, 0.0%si, 0.0%st
Cpu3 : 42.7%us, 1.7%sy, 0.0%ni, 54.6%id, 0.0%wa, 0.3%hi, 0.7%si, 0.0%st
Mem: 4018280k total, 2831016k used, 1187264k free, 313128k buffers
Swap: 7999472k total, 13612k used, 7985860k free, 1775196k cached
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
13685 afarber 15 0 112m 46m 2704 R 41.8 1.2 176:45.14 pref.pl
Thank you!
Alex
The rules of optimization are
In another comment, you say you don’t have performance problems, so you’re still at rule 1.
As for how to clear arrays and hashes, there’s one potential pitfall to avoid. Good practice is to always return copies of objects’ private data. Consider
Its output is
Returning a reference to private data gives a handle for making uncontrolled and likely surprising modifications.
If your code is sharing references, be sure to clear the same arrays and hashes rather than creating references to new ones. Otherwise, everyone else will go on using the old data without knowing anything has changed. In Perl terms, write
rather than