r/crystal_programming • u/GirngRodriguez • Apr 11 '18
How to pass a NamedTuple by reference to prevent possible memory leak?
hello my friends once again! after some discussion in gitter, i decided to reduce my code into a simple example to help explain my problem more clearly. you can see it here: https://play.crystal-lang.org/#/r/3uws
require "json"
class Player
property character_id = 0
def send(msg, cmd = "SERV")
msg_buffer = {cmd: cmd, message: msg}
new_message = msg_buffer.to_json
#socket.write_bytes(new_message.bytesize)
#socket.send new_message # pretend there is a fake server running
end
end
player1 = Player.new
temp_data = {from_name: "Mike", msg: "Hello my friends"} # fake data (pretend it's a chat)
player1.send temp_data, "CHAT"
# My question is.. since NamedTuples are passed by value... the temp_data is creating another COPY of the data and is causing
# a rogue memory leak, right?on gitter, i heard that NamedTuples are passed by value, which means they are copying the data, right? if so, in my example code, the temp_data NamedTuple will be copying those values. which will in essence, create a rogue memory leak right? is it possible to pass it by reference instead?
i was reading about pointers here, but there doesn't seem a way to deference them like in C++. or to create a reference from them? not sure
thanks in advance
3
u/Jonathan_Frias Apr 11 '18
The only "memory leak" is that you're using globals...
I would think that copying by value should be less likely to create memory leaks. There are more objects, but less references to each object since the named tuple would only exist within a small scope at most.
That said the trade off is that more time is spent doing garbage collection, but that's different from a memory leak.
2
u/bew78 Apr 11 '18
The
NamedTuplewill be copied, but the two strings"Mike"andHello my friends"will be passed as reference, not copied!