Program Tip

루비의 문자열 연결과 보간

programtip 2020. 10. 27. 23:08
반응형

루비의 문자열 연결과 보간


저는 루비 (처음 프로그래밍)를 배우기 시작했고 변수와 다양한 코드 작성 방법에 관한 기본적인 구문 질문이 있습니다.

Chris Pine의 "Learn to Program"은 저에게 이와 같은 기본 프로그램을 작성하도록 가르쳐주었습니다.

num_cars_again= 2
puts 'I own ' + num_cars_again.to_s + ' cars.'

이것은 괜찮지 만 ruby.learncodethehardway.com에서 튜토리얼을 우연히 발견하고 이와 같은 정확한 프로그램을 작성하도록 배웠습니다 ...

num_cars= 2
puts "I own #{num_cars} cars."

둘 다 같은 것을 출력하지만, 분명히 옵션 2는 훨씬 더 짧은 방법입니다.

한 형식을 다른 형식보다 사용해야하는 특별한 이유가 있습니까?


TIMTOWTDI (한 가지 이상의 방법이 있음)마다 장단점을 찾아야합니다. "문자열 연결"(첫 번째) 대신 "문자열 보간"(두 번째) 사용 :

장점 :

  • 적은 타이핑
  • 전화에 자동으로 to_s당신을 위해
  • Ruby 커뮤니티 내에서 더 관용적
  • 런타임 중에 더 빠르게 수행

단점 :

  • 자동으로 호출 to_s(문자열이 있다고 생각할 수 있으며 to_s표현이 원하는 것이 아니며 문자열이 아니라는 사실을 숨 깁니다)
  • 사용해야합니다 "대신하여 문자열을 구분하는 '(아마도 당신이 사용하는 습관을 가지고 ', 또는 이전에 사용하여 문자열을 입력하는 만 나중에 사용할 문자열 보간에 필요)

보간과 연결에는 모두 고유 한 강점과 약점이 있습니다. 아래에서는 연결을 사용할 위치와 보간을 사용할 위치를 명확하게 보여주는 벤치 마크를 제공했습니다.

require 'benchmark'

iterations = 1_00_000
firstname = 'soundarapandian'
middlename = 'rathinasamy'
lastname = 'arumugam'

puts 'With dynamic new strings'
puts '===================================================='
5.times do
  Benchmark.bm(10) do |benchmark|
    benchmark.report('concatination') do
      iterations.times do
        'Mr. ' + firstname + middlename + lastname + ' aka soundar'
      end
    end

    benchmark.report('interpolaton') do
      iterations.times do
        "Mr. #{firstname} #{middlename} #{lastname} aka soundar"
      end
    end
  end
  puts '--------------------------------------------------'
end

puts 'With predefined strings'
puts '===================================================='
5.times do
  Benchmark.bm(10) do |benchmark|
    benchmark.report('concatination') do
      iterations.times do
        firstname + middlename + lastname
      end
    end

    benchmark.report('interpolaton') do
      iterations.times do
        "#{firstname} #{middlename} #{lastname}"
      end
    end
  end
  puts '--------------------------------------------------'
end

아래는 벤치 마크 결과입니다.

Without predefined strings
====================================================
                 user     system      total        real
concatination  0.170000   0.000000   0.170000 (  0.165821)
interpolaton  0.130000   0.010000   0.140000 (  0.133665)
--------------------------------------------------
                 user     system      total        real
concatination  0.180000   0.000000   0.180000 (  0.180410)
interpolaton  0.120000   0.000000   0.120000 (  0.125051)
--------------------------------------------------
                 user     system      total        real
concatination  0.140000   0.000000   0.140000 (  0.134256)
interpolaton  0.110000   0.000000   0.110000 (  0.111427)
--------------------------------------------------
                 user     system      total        real
concatination  0.130000   0.000000   0.130000 (  0.132047)
interpolaton  0.120000   0.000000   0.120000 (  0.120443)
--------------------------------------------------
                 user     system      total        real
concatination  0.170000   0.000000   0.170000 (  0.170394)
interpolaton  0.150000   0.000000   0.150000 (  0.149601)
--------------------------------------------------
With predefined strings
====================================================
                 user     system      total        real
concatination  0.070000   0.000000   0.070000 (  0.067735)
interpolaton  0.100000   0.000000   0.100000 (  0.099335)
--------------------------------------------------
                 user     system      total        real
concatination  0.060000   0.000000   0.060000 (  0.061955)
interpolaton  0.130000   0.000000   0.130000 (  0.127011)
--------------------------------------------------
                 user     system      total        real
concatination  0.090000   0.000000   0.090000 (  0.092136)
interpolaton  0.110000   0.000000   0.110000 (  0.110224)
--------------------------------------------------
                 user     system      total        real
concatination  0.080000   0.000000   0.080000 (  0.077587)
interpolaton  0.110000   0.000000   0.110000 (  0.112975)
--------------------------------------------------
                 user     system      total        real
concatination  0.090000   0.000000   0.090000 (  0.088154)
interpolaton  0.140000   0.000000   0.140000 (  0.135349)
--------------------------------------------------

결론

If strings already defined and sure they will never be nil use concatination else use interpolation.Use appropriate one which will result in better performance than one which is easy to indent.


@user1181898 - IMHO, it's because it's easier to see what's happening. To @Phrogz's point, string interpolation automatically calls the to_s for you. As a beginner, you need to see what's happening "under the hood" so that you learn the concept as opposed to just learning by rote.

Think of it like learning mathematics. You learn the "long" way in order to understand the concepts so that you can take shortcuts once you actually know what you are doing. I speak from experience b/c I'm not that advanced in Ruby yet, but I've made enough mistakes to advise people on what not to do. Hope this helps.


If you are using a string as a buffer, I found that using concatenation (String#concat) to be faster.

require 'benchmark/ips'

puts "Ruby #{RUBY_VERSION} at #{Time.now}"
puts

firstname = 'soundarapandian'
middlename = 'rathinasamy'
lastname = 'arumugam'

Benchmark.ips do |x|
    x.report("String\#<<") do |i|
        buffer = String.new

        while (i -= 1) > 0
            buffer << 'Mr. ' << firstname << middlename << lastname << ' aka soundar'
        end
    end

    x.report("String interpolate") do |i|
        buffer = String.new

        while (i -= 1) > 0
            buffer << "Mr. #{firstname} #{middlename} #{lastname} aka soundar"
        end
    end

    x.compare!
end

Results:

Ruby 2.3.1 at 2016-11-15 15:03:57 +1300

Warming up --------------------------------------
           String#<<   230.615k i/100ms
  String interpolate   234.274k i/100ms
Calculating -------------------------------------
           String#<<      2.345M (± 7.2%) i/s -     11.761M in   5.041164s
  String interpolate      1.242M (± 5.4%) i/s -      6.325M in   5.108324s

Comparison:
           String#<<:  2344530.4 i/s
  String interpolate:  1241784.9 i/s - 1.89x  slower

At a guess, I'd say that interpolation generates a temporary string which is why it's slower.

참고URL : https://stackoverflow.com/questions/10076579/string-concatenation-vs-interpolation-in-ruby

반응형