Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crystal language: what to use instead of runtime String::to_sym

I am trying to convert a ruby program to crystal.

And i am stuck with missing string.to_sym

I have a BIG xml file, which is too big to fit in memory. So parsing it all is out of question. Fortunately i do not need all information, only a portion of it. So i am parsing it myself, dropping most of the lines. I used String::to_sym to store the data, like this:

:param_name1 => 1
:param_name2 => 11
:param_name1 => 2
:param_name2 => 22
:param_name1 => 3
:param_name2 => 33

What should i use in crystal? Memory is the bottleneck. I do not want to store param_name1 multiple times.

like image 511
jsaak Avatar asked Sep 12 '15 07:09

jsaak


1 Answers

If you have a known list of parameters you can for example use an enum:

enum Parameter
  Name1
  Name2
  Name3
end

a = "Name1"
b = {'N', 'a', 'm', 'e', '1'}.join
pp a.object_id == b.object_id # => false
pp Parameter.parse(a) == Parameter.parse(b) # => true

If the list of parameters is unknown you can use the less efficient StringPool:

require "string_pool"

pool = StringPool.new

a = "param1"
b = {'p', 'a', 'r', 'a', 'm', '1'}.join

pp a.object_id == b.object_id # => false
a = pool.get(a)
b = pool.get(b)
pp a.object_id == b.object_id # => true
like image 200
Jonne Haß Avatar answered Sep 21 '22 03:09

Jonne Haß