If we have a string like this "1,2,3,4,5" and we parse it using a split function to get individual elements, Ruby allocates a new string object for each element. If you process a big file, which has a lot of duplicated values, for example a lot of 0s, then returning frozen strings will save a lot of time and memory since interpreter wouldn't have to create these new objects - it could return a reference to the frozen string - and it wouldn't need to clean up after them.
So instead of this: (every string object is unique)
2.4.1 :007 > "1,2,3,4,5,6".split(',').map(&:object_id)
=> [70280975267840, 70280975267820, 70280975267800, 70280975267780, 70280975267760, 70280975267740]
2.4.1 :008 > "1,2,3,4,5,6".split(',').map(&:object_id)
=> [70280978671420, 70280978671400, 70280978671380, 70280978671360, 70280978671340, 70280978671320]
I would like to see this: ( we get the same string objects in the first and in the second run )
2.4.1 :007 > "1,2,3,4,5,6".split(',').map(&:object_id)
=> [70280975267840, 70280975267820, 70280975267800, 70280975267780, 70280975267760, 70280975267740]
2.4.1 :008 > "1,2,3,4,5,6".split(',').map(&:object_id)
=> [70280975267840, 70280975267820, 70280975267800, 70280975267780, 70280975267760, 70280975267740]
Of course, this would need to be some kind of opt-in mechanism, which for example allows you to specify the list of frozen strings you would like to use since freezing each word in a file sounds like asking for trouble.
So ideally the interface would be like this:
"1,2,3,4,5,6".split(',', frozen_strings: [-'1', -'2', -'3', -'4', -'5', -'6'])
Is there any way to do this in Ruby without writing a C extension? Maybe using some external libraries like CSV parsers?