Blog: Crystal: Concurrency with easier syntax than Go

I just wanted to share a blog post I just wrote, comparing a simple concurrency pattern I’ve often used in Go, which I tried to implement in Crystal:

https://rillabs.com/posts/crystal-concurrency-with-easier-syntax-than-go

I posted on HN as well, although doesn’t seem to have taken off there (yet): https://news.ycombinator.com/item?id=24384292

8 Likes

Nice! The equivalent of defer is begin/ensure.

1 Like

Nice! The equivalent of defer is begin/ensure.

Aha, thanks! Gotta check that!

EDIT: Updated the post with “ensure” now, thanks! :slight_smile:

This is fantastic, I love when people show the code for comparison. It really highlights the differences in ergonomics between the languages. I did the same when comparing Crystal to Rust and, even though the ergonomics weren’t the point of that post, people still mentioned it a lot. :-D

One of the Disqus comments makes a good point, though: have you tried running the Crystal code with --release and CRYSTAL_WORKERS environment variable set to the number of CPU cores on your machine (defaults to 4)? That may or may not make it fast enough to outperform the Go code (seriously, it might!), but even if it doesn’t it’ll likely be a lot closer than without it.

1 Like

Thanks for kind words :slight_smile: And thanks for pointing out the compiler flags etc. Yes, for performance comparison, I’ve been using those. Updated the post now, to clarify that, should have done it from the start for sure.

That is a very interesting post comparing with Rust as well! Didn’t expect Crystal to win out against Rust :smiley: Maybe gives me more excuses for not need to take the effort to learn Rust, haha.

1 Like

I don’t think Crystal can beat Go here. I suspect a lot of time is spent in the runtime, sending stuff through channels, doing context switches, etc. Go is really optimized for that stuff, at the register level.

Out of curiosity: why are two fibers or goroutines even needed here? Reading from a file will never block so you can just read from it and parse it as you go. I guess it’s just to demonstrate the usage of fibers and channels?

FWIW its --release. Notice the two -. I don’t think it would work with just one.

FWIW its --release . Notice the two - . I don’t think it would work with just one.

Fixed, thanks!

1 Like

Exactly. Although I have been playing a lot with the idea of a very simple flow-based programming framework with re-usable pluggable components for common tasks, and for this, a general file-reader component does make sense [1] … although it would have a little more structure around it than in the example above, such as an object with the output channel stored in a field.

[1] In the one program I developed using these ideas, I do use a file reader, although it is specialized for reading data in turtle format. But a general file reader would surely be useful as well.