ThePrimeagen / tyrone-biggums

Clearly a repo about websockets and their comparison...
Other
463 stars 56 forks source link

go-server suggestions #2

Closed davidmdm closed 2 years ago

davidmdm commented 2 years ago

Hi,

I loved your NodeJS/TS vs Go video and I thought I would check out the code, and I wanted to make some suggestions... In the end it snowballed, and there seems to be a lot of changes but I assure you it is mostly just gofmt that has formatted the code.

Here are the notable changes suggestions by order of importance:

Anyways, Loved your video, was hoping you would check out these suggested changes, and no worries if you don't want to merge. I did go a little overboard.

Best of luck, and can't wait to see your next video.

ThePrimeagen commented 2 years ago

My Friend. I am pretty weak at Go, so this is great. I am going to leave this PR up and use it for the next version of this program.

Could you help me understand this pointer thing? When I allocate and pass without pointer, does it copy? Or is it more like rust and move "ownership?"

Any additional resources would be great.

davidmdm commented 2 years ago

Thanks. Sure no problem. Basically Go uses escape analysis to see if a variable will live beyond the lifetime of the function. If it can safely do so it will allocate it on the stack, and if it cannot it will allocate it on the heap.

So in your case by making FromSocket -> *Message Because we are returning a pointer to a message the message value itself must outlive the function and will be allocated on the heap, where it will be referenced by the pointer you are returning.

By returning the value, we know that we will be passing the Message by value (copying) around a lot, but avoids putting pressure on the GC finding and eliminating those Messages that were previously being allocated on the heap.

Does this mean that Values over Pointers is always going to give superior performance? Not always. Sometimes copying large pieces of memory between functions is not as effective as copying a pointer to that memory around. In your case though, I am thinking it is a fair bet that it should relieve pressure on the Go GC, but it would have to be proven.

You can read this article about escape analysis in Go for more details: https://medium.com/a-journey-with-go/go-introduction-to-the-escape-analysis-f7610174e890

ThePrimeagen commented 2 years ago

I'm just starting the go client now. I'll be using this as my strategy.

I'll ping you once it's done, if you could give it a review that'd be great.

ThePrimeagen commented 2 years ago

if you haven't looked at the latest implementation, i tried to follow your advice ;)

ThePrimeagen commented 2 years ago

i closed this because the server is completely different.