Monday, 20 April 2015

Difference between += and .concat


example:

2.1.1 :009 > x="saritha"
 => "saritha"
2.1.1 :010 > x+="srinivas"
 => "sarithasrinivas"
2.1.1 :011 > x.object_id
 => 19461520
2.1.1 :012 > x+="sree"
 => "sarithasrinivassree"
2.1.1 :013 > x.object_id
 => 19365720
2.1.1 :014 > x="hello"
 => "hello"
2.1.1 :015 > x.object_id
 => 19016160
2.1.1 :016 > x.concat("hi")
 => "hellohi"
2.1.1 :017 > x.object_id
 => 19016160
 2.1.1 :018 > x.concat(2)
 => "hellohi\u0002"
2.1.1 :019 > x.object_id
 => 19016160
2.1.1 :020 > i=10
 => 10

Based on above exple, += always creates a new object to perform string operation and .concat work on existing object only. so concat() is faster than +.
another exmple:
2.1.1 :021 > x = "hello"
 => "hello"
2.1.1 :022 > x.object_id
 => 19923680
2.1.1 :023 > x << "joy"
 => "hellojoy"
2.1.1 :024 > x.object_id
 => 19923680
2.1.1 :025 > x << "2015"
 => "hellojoy2015"
2.1.1 :026 > x.object_id
 => 19923680

<< alias for .concat
Fair question. The plus symbol, it seems, creates an intermediary copy of the variables before combining them, whereas << and concat directly concatenate the variables to each other without first producing an intermediary copy.

No comments:

Post a Comment