Search code examples
c#asp.net-mvcentity-frameworkentity-framework-6

Asp.Net MVC slow function for retrieving random numbers from database


I have function called getWords(int wrNum) which returns wrNum number random numbers from database using entity framework and when wrNum is 300 this function takes 10 seconds of time approximately. I can't understand why it takes so much time. Please help what is wrong with my code?

public List<string> getWords(int wrNum)
{
    IDVLTest d3 = new DVLTest();
    for (int i = 0; i < wrNum;i++ )
    {
        string word = d3.getRandomWord().Text;
        Words.Add(new WordView { Word = word, Status = WordStatus.Right });
    }
    return Words.Select(w=>w.Word).ToList();
}

public class DVLTest:IDVLTest
{
...
    public Word getRandomWord()
    {
        Random r = new Random();
        int i = r.Next(DVL_Entitie.Words.Count());
        return DVL_Entitie.Words.ToList().ElementAt(i);
    }
...
}

Solution

  • Because you are retrieving the entire list from the database in every iteration and database access in general is expensive as it occurs out of process and usually over a network (the database and the application/process usually do not reside on the same server). You should retrieve the list once outside of the for loop and then pass the retrieved list to the method getRandomWord as a parameter.

    DVL_Entitie.Words.Count() // offending line
    DVL_Entitie.Words.ToList() // offending line