Posts

Showing posts from December, 2018

[Javascript] Pass by Reference or Pass by Value?

Connection between variable, value and memory A variable is just a pointer to a location in memory. When you create a variable, your program allocates a space in memory, remembers it so that you can assign value to it and retrieve the value when you want. The 'reference' in 'pass-by-reference' refers to memory location. The 'value' in 'pass-by-value' refers to the actual value in the memory location. Why does this matter? When you use pass-by-value, it means that any argument you pass to a function only have their values copied and transferred to parameters inside the function definition. In other words, the parameters inside the function are not the same as the variables you passed in as arguments. When I say the 'same', even though their value is same, if you change one of them, the other will not change (if it is pass-by-reference, the other will change). Below is an example of pass-by-value: // A pseudo-code example of pass-by-va

[ORM] Eager Loading and N+1 Query Problem

What is N+1 query problem? When your code loads the children in a parent-child relationship via the parent, most ORM have lazy-loading enabled by default, so queries are issued for the parent record, and then one query for EACH child record. As you can expect, doing N + 1 queries instead of a single query will floor your database with queries; something to avoid.  Consider this code: #Articles model class Article < ActiveRecord::Base     belongs_to :author end  #Authors model class Author < ActiveRecord::Base     has_many :posts end If you then ran: #In our controller @recent_articles = Article.order(published_at: :desc).limit(5) #in our view file @recent_articles.each do |article|     Title: <%= article.title %>     Author:<%= article.author.name %> # <-- this will trigger N+1 query end You would send 6 (5+1) queries to the database. 1 to fetch 5 recent articles, and then 5 for their corresponding authors. Remember: it is faster to send

[Websites] Eager and Lazy Loading

[Website] Eager Loading, Lazy Loading A simple explanation is this: 1. Eager loading : you do everything when asked. Classic example is when you multiply two matrices. You do all the calculations. 2. Lazy loading : you only do a calculation when required. In the previous example, you don't do any calculations until you access an element of the result matrix. 3. Over-eager loading : this is where you try and anticipate what the user will ask for and preload it. Websites  In the context of a website, you can imagine that there are three ways the image loading could work on this page: ( eager );  Load only the displayed images on page load and load the others if/when they are required ( lazy ); and  Load only the displayed images on page load. After the page has loaded preload the other images in the background in case you need them ( over-eager ).  https://stackoverflow.com/questions/1299374/what-is-eager-loading