Sets again

Ivan Senji ivan.senji_REMOVE_ at _THIS__gmail.com
Mon Feb 20 00:42:28 PST 2006


Lionello Lunesu wrote:
>>How about in for arrays for consistency with AA's:
>>
>>void foo(char[] )
>>{
>>char[] arr = "abcdef";
>>//...
>>if('d' in arr) { ... }
>>}
>>
> 
> 
> NO! Please don't do this. The operation is O(n). If will be useful perhaps 
> for "if (day in Weekdays)", but the system is extremely unscalable, and 
> using "in" on a larger array will harm performance. I don't think it's a 
> good idea to hide such a potential performance hit behind a small word like 
> "in".
> 
> (In fact, I generally think the costly operations should get long, 
> complicated names, so they don't get used too often)
> 
> Now if the array were sorted, one could do a binary search, which is not all 
> too bad. But this still needs special syntax, since the compiler should 
> enforce the sorting.
> 

O(n) can be an expensive operation, but if used with arrays with less 
then 10 elements, it would not only be simpler to code, but also almost 
as fast as any other search algorithm. Very often i have such small 
arrays and having to do:
bool foundit=false;
foreach(....){if(...)foundit=true;}

is not only as equally efficient but also much harder to write.

Not having in operator for arrays because of O(n) is like saying 
vector<int> in C++ is bad because you can have milions of elements and 
linear search is slow. It is all about choosing the right tool for the 
job. If someone want's a container with many elements he will probably 
use a container implementning binary search or some other faster 
element, but in many cases simple linear search in a couple of elements 
is more than enough.

One thing that would be very nice is having overloadable in operator for 
user defined types.

PS Another positive side about having in for arrays would be 
consistency, we have it for AA's, having it for normal arrays and 
classes would just make it make more sence to have.





More information about the Digitalmars-d mailing list