0

Suppose I need to add and remove elements from an array where they must be unique.

Class A {
    protected $elements = [];

    function add($element) {
        if (!in_array($element, $this->elements)) {
            $this->elements[] = $element;
        }
    }

    function remove($element) {
        if (($key = array_search($element, $this->elements)) !== false) {
            unset($this->elements[$key]);
        }
    }
}

This looks fine but if $elements has a great deal of elements in it PHP will need to iterate every time add() or remove() is called. Instead I can do this:

Class A {
    protected $elements = [];

    function add($element) {
        $this->elements[$element] = true;
    }

    function remove($element) {
        unset($this->elements[$element]);
    }
}

Which should be performing at the same speed regardless of the number of elements, but I may be completely wrong about this and that is the point of this question.

I have been doing this all over the place in my codes but it is bugging me that I am storing a bunch of useless information (in this example some true booleans) that serve absolutely no purpose but can not go without them. This appears as some kind of a flaw and makes me thing that this method is not completely bulletproof as I may think.

Is this way of storing information in arrays any better than the, what I suppose would be considered the proper way, first example and are there any downsides to it, except storing needless information?

php_nub_qq
  • 15,199
  • 21
  • 74
  • 144

1 Answers1

1

Your second solution will be significantly faster than the first one.

The downsides are that it will take significantly more memory and that you can store only integers and strings like that.

If you are doing a lot of add/remove on reasonably high number of elements - then go with the second solution.

If you are expecting hundreds of thousands or even million of elements - then the second solution may go with out of memory exception - so you should use the first one.