I created routine Match, Team, etc models to create a soccer manager game and included many known statistics as attributes (total shots, shots wide, fouls, corners,..) in the Match model. I would like to give the statistics for each halftime. Therefore I created attributes like HomeTeamFirstHalfGoals and AwayTeamSecondHalfCorners. I plan to calculate the totals like
HomeTeamTotalGoals = HomeTeamFirstHalfGoals + HomeTeamSecondHalfGoals
within Match model and display some or all those stats as a LeagueTable when requested by the user. I suppose that the user may want to see different tables like all matches played within last week or whole fixture including some of the calculable attributes like TotalGoals etc. or the whole match list of a specific team/season.
However, the code is working too slowly. I do not know whether it is due to development environment and since I have little knowledge and more confusion about mysql, I wonder how I should design the match table.
The question is, (since I heard the notion of database query, which as I see, costs the server time and cpu) should I keep the number of attributes (like AwayTeamSecondHalfCorners) minimal and calculate the dependent ones (like TotalGoals) on the fly or do the opposite to keep overhaul at the server at a minimum?
Note: I suppose everyone knows that it is so easy to create a new column by typing A3=(A1+A2) in Excel. I am confused whether it is as easy as this in ruby views or it is more efficient to do it in the mysql table? Since I have no programming background, a guide to simple sources is welcome.
Lots of ways to approach this. First thing would be to start identifying which parts of your code are fast and which are not – I’d use Ruby’s benchmark library ( http://www.ruby-doc.org/stdlib-1.9.3/libdoc/benchmark/rdoc/Benchmark.html ).
In general, I’d recommend storing all the discrete data, and defining methods to calculate everything that can be derived from the discrete data. So, I’d say that a team’s total goals would be something like:
With whatever logic needs to be in place to do that math. Arithmetic like this is pretty fast and shouldn’t cause any code complaints.
One thing that would cause big slowdowns is if your database is missing any indexes – any time you have a foreign key (typically anything that ends in _id; e.g., if a Game has an away_team_id and a home_team_id, then those are probably both foreign keys), there should be a corresponding index in your database. To add an index, create a new database migration, then drop in some code like this:
That’ll speed up any time you’re looking up the games that a team played by a very large margin.