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?