Module: Datadog::Core::Utils::SafeDup

Defined in:
lib/datadog/core/utils/safe_dup.rb

Overview

Helper methods for safer dup

Class Method Summary collapse

Class Method Details

.frozen_dup(v) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/datadog/core/utils/safe_dup.rb', line 25

def self.frozen_dup(v)
  # For the case of a String we use the methods -@
  # That method are only for String objects
  # they are faster and chepaer on the memory side.
  # Check the benchmark on
  # https://github.com/DataDog/dd-trace-rb/pull/2704
  if v.is_a?(String)
    -v if v
  else
    v.frozen? ? v : v.dup.freeze
  end
end

.frozen_or_dup(v) ⇒ Object

String#+@ was introduced in Ruby 2.3



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/datadog/core/utils/safe_dup.rb', line 9

def self.frozen_or_dup(v)
  # For the case of a String we use the methods +@ and -@.
  # Those methods are only for String objects
  # they are faster and chepaer on the memory side.
  # Check the benchmark on
  # https://github.com/DataDog/dd-trace-rb/pull/2704
  if v.is_a?(String)
    # If the string is not frozen, the +(-v) will:
    # - first create a frozen deduplicated copy with -v
    # - then it will dup it more efficiently with +v
    v.frozen? ? v : +(-v)
  else
    v.frozen? ? v : v.dup
  end
end