roxen.lists.pike.general

Subject Author Date
Re: Arrays, multisets, mappings: avoiding unnecessary memory Henrik_Grubbström <grubba[at]roxen[dot]com> 07-09-2009
 (re)assigns
On Mon, 7 Sep 2009, Arjan van Staalduijnen wrote:

> In various pieces of code I am bluntly doing frequent operations such
> as:
>
> 	ids -= (< identifier >);
> or
> 	ids |= ({ identifier });
> or
> 	m_delete(ids, identifier);
>
> without previously checking if 'identifier' is actually available in
> 'ids'. In most delete operations it is most-likely 'identifier' was
> already removed earlier, while for the add operations 'identifier' in
> most cases it is already an element of the ids variable.
>
> Since operations on arrays, multisets and mappings are usually
> destructive I am guessing my pieces of code might actually result in
> various memory copy operations, even though the output has the same
> value as the input.

Correct, the two first operations semantically copy the value in the 
variable.

For the multiset case, you can use the syntax

   ids[identifier] = 0;

to remove an element from the multiset, and

   ids[identifier] = 1;

to add a missing element to the multiset.

For the array case, I'd attempt to avoid doing operations that change the 
size of the array.

In the mapping case, copying of data is usually deferred until the first 
change. m_delete() is a destructive function, so there's no copying even 
on change (except when the mapping size passes certain thesholds).

> Is my assumption correct, and would it be a good thing to check
> has_index/has_value before adding or removing any identifier for the
> above-mentioned examples, or does pike take care of that internally?
>
> If pike handles the check internally, is there still a purpose to do a
> has_value-check before adding an element, just to avoid the creating of
> a temporary array (containing just the identifier value) for an
> operation like:
>
> 	ids |= ({ identifier });
> 
> or would the penalty of the extra has_value cost more than it would
> save?

See above.

> Regards,
>
> Arjan

--
Henrik Grubbström					<grubba[at]roxen.com>
Roxen Internet Software AB