I have some arrays storing the possible parameters for some 3D printer commands. I use this to check if the command is legal. I am confused about where I should put these ar
I think that the defining array a property is making more sense, as arrays defined inside the methods are created on every call.
But I want to make another point. If you have rather large arrays to look up value in, it is more important how you structure them. I would suggest this:
array(
82 => true,
83 => true,
84 => true,
104 => true,
106 => true,
107 => true,
109 => true,
140 => true,
190 => true
);
array(
0 => true,
1 => true,
20 => true,
21 => true,
28 => true,
90 => true,
91 => true,
92 => true
);
array(
0 => true,
1 => true
);
Having this structure you can use isset (O(1)
) instead of in_array (O(n)
).
Here are some other questions regarding isset vs. in_array:
what is faster: in_array or isset? [closed]
in_array vs isset - perfomance
And here are some posts with benchmarks:
The last one is rather old, but I think the ratio holds.
So to sum up. When you use isset the searching time is constant (it actually might vary, but this can be ignored). When you use in_array the searching time depends on element position (and so on array size). Even on small arrays isset works faster.