Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.increment vs += 1

I have a Picture model that contains a variable for a view count (integer). The view count is incremented by +1 every time someone views the Picture object.

In getting this done, what is the difference between

   @picture.view_count += 1    @picture.save 

and

   @picture.increment(:view_count, 1) 

also if i use increment, is .save necessary?

like image 526
James Pleasant Avatar asked Jul 16 '12 06:07

James Pleasant


People also ask

Is i ++ the same as I 1?

These two are exactly the same. It's just two different ways of writing the same thing. i++ is just a shortcut for i += 1 , which itself is a shortcut for i = i + 1 . These all do the same thing, and it's just a question of how explicit you want to be.

Which one is faster i ++ or ++ i?

++i is sometimes faster than, and is never slower than, i++. For intrinsic types like int, it doesn't matter: ++i and i++ are the same speed. For class types like iterators or the previous FAQ's Number class, ++i very well might be faster than i++ since the latter might make a copy of the this object.

Is i ++ faster than i i 1?

As i++ does automatic typecasting and uses a compiler instruction which internally uses iadd instruction, i=i+1 is faster than i++.

What is the meaning of a += 1?

i+=i means the i now adds its current value to its self so let's say i equals 10 using this += expression the value of i will now equal 20 because you just added 10 to its self. i+=1 does the same as i=i+1 there both incrementing the current value of i by 1. 3rd January 2020, 3:15 AM.


2 Answers

The source of increment is below, which initializes attribute to zero if nil and adds the value passed as by (default is 1), it does not do save, so .save is still necessary.

def increment(attribute, by = 1)   self[attribute] ||= 0   self[attribute] += by   self end 
like image 121
xdazz Avatar answered Sep 22 '22 21:09

xdazz


I often use counter_cache and increment_counter in that case.

like this:

Picture.increment_counter(:view_count, @picture.id) 

This way is more simple and faster than self-made method.

Incidentally, ActiveRecord::CounterCache has also decrement_counter.

http://api.rubyonrails.org/classes/ActiveRecord/CounterCache/ClassMethods.html

like image 38
nekova Avatar answered Sep 21 '22 21:09

nekova