Why do the same work about 'IndexOfAny' and 'indexOf' function?

ketmar via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jan 9 05:25:08 PST 2015


On Fri, 09 Jan 2015 13:06:09 +0000
FrankLike via Digitalmars-d-learn <digitalmars-d-learn at puremagic.com>
wrote:

> On Friday, 9 January 2015 at 10:02:53 UTC, ketmar via 
> Digitalmars-d-learn wrote:
> 
> >   import std.algorithm, std.stdio;
> >
> >   void main () {
> >     string s = "he is at home";
> >     if (["home", "office", "sea", "plane"].canFind!((a, string 
> > b) => b.canFind(a))(s)) {
> >       writeln("got it!");
> >     } else {
> >       writeln("alas...");
> >     }
> >   }
> 
> Thank you.
> 
> The code is the best,and it's better than indexOfAny in C#:
> 
> /*  places.canFind!(a => strWhere.canFind(a));  */
> 
> By  auto r = benchmark!(f0,f1, f2, f3,f4)(10_0000);
> 
> Result is :
> filter is          42ms 85us
> findAmong is       37ms 268us
> foreach indexOf is 37ms 841us
> canFind is         13ms
> canFind indexOf is 39ms 455us
> 
> -----------------------5 functions--------------------------
> import  std.stdio, std.algorithm,std.string;
> 
> auto places = [ "home", "office", "sea","plane"];
> auto strWhere = "He is in the sea.";
> 
> void main()
> {
>    auto where = places.filter!(a => strWhere.indexOf(a) != -1);
> 	writeln("0 Result is  ",where);
> 	
> 	auto where1 = findAmong(places,strWhere);
> 	writeln("1 Result is  ",where1);
> 	
> 	string where2;
> 	foreach(a;places)
> 	{
> 		if(strWhere.indexOf(a) !=-1)
> 		{
> 		  where2 = a;
> 		 break;
> 		}
> 	}
> 	writeln("2 Result is  ",where2);
> 	
> 	auto where3 = places.canFind!(a => strWhere.canFind(a));
> 	writeln("3 Result is  ",where3);
> 	
> 	auto where4 = places.canFind!(a => strWhere.indexOf(a) != -1);
> 	writeln("4 Result is  ",where4);
> }
> 
> Frank
if you *really* concerned with speed here, you'd better consider using
regular expressions. as regular expression can be precompiled and then
search for multiple words with only one pass over the source string. i
believe that std.regex will use variation of Thomson algorithm for
regular expressions when it is able to do so.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 181 bytes
Desc: not available
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20150109/e6a50c04/attachment.sig>


More information about the Digitalmars-d-learn mailing list