String concatenation in Ruby

前端 未结 16 1118
青春惊慌失措
青春惊慌失措 2020-11-28 01:28

I am looking for a more elegant way of concatenating strings in Ruby.

I have the following line:

source = \"#{ROOT_DIR}/\" << project <<          


        
16条回答
  •  清酒与你
    2020-11-28 01:34

    Let me show to you all my experience with that.

    I had an query that returned 32k of records, for each record I called a method to format that database record into a formated string and than concatenate that into a String that at the end of all this process wil turn into a file in disk.

    My problem was that by the record goes, around 24k, the process of concatenating the String turned on a pain.

    I was doing that using the regular '+' operator.

    When I changed to the '<<' was like magic. Was really fast.

    So, I remembered my old times - sort of 1998 - when I was using Java and concatenating String using '+' and changed from String to StringBuffer (and now we, Java developer have the StringBuilder).

    I believe that the process of + / << in Ruby world is the same as + / StringBuilder.append in the Java world.

    The first reallocate the entire object in memory and the other just point to a new address.

提交回复
热议问题