Avoid slow string concatenation

이 페이지는 아직 한국어로 제공되지 않으며 번역 작업 중입니다. 번역에 관한 질문이나 의견이 있으시면 언제든지 저희에게 연락해 주십시오.

Metadata

ID: ruby-best-practices/concat-strings

Language: Ruby

Severity: Notice

Category: Best Practices

Description

The rule to avoid slow string concatenation in Ruby is essential for writing efficient and fast-performing code. String concatenation using the += operator is slower because it creates a new string object every time it’s used. This can lead to performance issues, especially in loops or large programs where numerous string concatenations might be happening.

Instead, the << operator, also known as the append operator, should be used for string concatenation in Ruby. The << operator modifies the original string, avoiding the creation of multiple unnecessary string objects. This results in faster execution time and lower memory usage, which is especially beneficial in larger applications or systems with limited resources.

Therefore, good coding practice in Ruby suggests using << for string concatenation instead of +=. For instance, output << "<p>#{text}</p>" is more efficient than output += "<p>#{text}</p>". Following this rule will help you write cleaner, faster, and more resource-efficient Ruby code.

Non-Compliant Code Examples

output = ''
output += '<h1>Page title</h1>'
output += '<h3>Sub heading</h3>'

texts.each do |text|
  output += "<p>#{text}</p>"
end

Compliant Code Examples

output = ''
output << '<h1>Page title</h1>'
output << '<h3>Sub heading</h3>'

texts.each do |text|
  output << "<p>#{text}</p>"
end
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis

PREVIEWING: rtrieu/product-analytics-ui-changes