A database table (id, name ,...) There are 0.1 million records. It may take a long time to search for name = 'guoguo'. However, if you create an index for the name, then, query with name = 'guoguo' will become very fast (how fast? You can try it yourself ).
Correspondingly, sometimes our code uses List <T> and Array to store a group of data. Let's take an example.
Define the Data Type:
ID { ; Name { ; Age { ;
. You can use the following code to find the corresponding UserInfo from the List by name:
List<UserInfo> UserInfo GetUserInfoByName( ( i = ; i < _userinfos.Count; i++= (ui.Name == UserInfo GetUserInfoByName_Find( _userinfos.Find((temp) => temp.Name ==
Both methods are compared and searched by traversing the list. I did an experiment. If the list contains 0.1 million records, it takes 5th times to search for 1000 million elements respectively:
GetUserInfoByName |
1877 Ms |
GetUserInfoByName_Find |
2290 Ms |
That is to say, the average time is about 2 milliseconds (the Find efficiency is lower );
OK. Next we will try to create an index for the List using the database method.
List<UserInfo> { =<, UserInfo> <, UserInfo> userIndex = Dictionary<, UserInfo> ( item =
The MakeIndex method is called in the set attribute of Userinfos. The query method should be written as follows:
UserInfo GetUserInfoByNameEx(
So simple? Yes, it is so simple and efficient. Compare with the preceding two methods:
Index creation + SEARCH 0.1 million times = 36 ms!
The reason is that the time complexity of the Dictionary [Key] method is O (1), which is almost time-consuming.
All the sample code is as follows:
Main (<UserInfo> userinfos = List <UserInfo> (I =; I <*; I ++ ====. format (nameToFind = userinfos [* (I =; I <; I ++. format (I =; I <; I ++. format (I =; I <*; I ++. format (<UserInfo> List <UserInfo >{= <, UserInfo> UserInfo GetUserInfoByName (I =; I <_ userinfos. count; I ++ = (ui. name = UserInfo GetUserInfoByName_Find (_ userinfos. find (temp) => temp. name = <, UserInfo> userIndex = Dictionary <, UserInfo> (item = UserInfo GetUserInfoByNameEx (ID {; Name {; Age {;Sample Code