Observer design pattern in Crystal language
A post where I want to share my thoughts regarding an implementation of an Observer design pattern in Crystal language.
Whether you are an experienced developer or a newbie, using programming language regularly or just learning it, anyway, someday you will have few ways to code things and ask your self which implementation is faster, which is more efficient and which should you use in your particular case.
Benchmarking usually helps to answer this questions, but a lot of people associate benchmarking with a lot of work. Fortunately, in Crystal programming language benchmarking requires minimal effort with a great feedback. It has a built-in module Benchmark, which currently can work in two modes: compare tasks and measure time. I think the most important part in code benchmarking is comparing tasks with each other, so let’s write a little example with Benchmark.ips method:
Here we want to simply compare performance of two methods:
Array#?. Let’s run our source file and see what happens:
Report says that
Array# 1.12x times slower than
Array#?. Ah, how it is easy to benchmark, isn’t it?
Note: according to the documentation, Crystal benchmarks should always be running with
--release flag. Never miss awesome optimizations of the compiler while benchmarking!
Let’s look at more examples:
Int32#to_s is faster than interpolation when you just want to convert integer to string. But with interpolation we also can perform a concatenation, which is much more efficient than concatenation with
But for really big strings we have to use
String.build because of the benchmark:
The next example has been taken from a Fast Ruby - collection of common Ruby idioms. Of course, it was ported to Crystal:
Hash#? with symbols wins. Awesome!
There (in Fast Ruby) you may find a lot of good examples of tasks to compare and try it in Crystal.
Next time you’re considering which method is faster, set up and run a quick benchmark. But you have to understand, benchmarking does not give you a complete picture about why your code might run slower, but it gives you a good image about how your code is performing. Happy benchmarking!
Source code for used examples you may found on Github Gist.
All examples were run with Crystal 0.8.0.