Swapping variables in realtime One process that we see a lot is swapping a config variable for a new one without restarting the running process. Again, we can do this pretty easily with a mutex. Below is some example code that swaps a very simple config struct into an App struct safely with a mutex. Again we can benchmark it with go test. Nice and quick, no allocations apart from the obvious initial ones. Can we make this faster? Well I reckon the answer is yes if we use the atomic package. Something like this.. This bit of code is using one of the functions available to us — specifically compare and swap pointers. Compare and Swap This basically does the following in an atomic way IF old version is what we think it isTHEN swap ptr to new version and TRUEELSE false So how does this perform? Not too badly. There’s about an 8x speed up over the mutex. There is a slightly simpler version of this that just loads a value into a pointer. The compare and swap algorithm allows you to confirm that nothing has changed at the point of you deciding to set the new variable and the actual setting of the new variable. I think I should point out here that this bit of code uses the unsafe package to manage some pointer swapping — this isn’t necessarily to everyones taste and it also won’t work in some environments — for example. If you can handle those caveats and if you’re doing a lot of swapping of variables, then it might be a valid performance tweak. play.golang.org There’s also another interesting struct you can use from the atomic package. atomic.Value{} This is a more complete way of pointer swapping, and accepts an interface, meaning you can store and load practically anything. There is one caveat to its use. It must never be copied. Bad things will happen — although to be honest, I don’t know if this is just because you create multiple copies pointing to the same underlying memory, or there’s a specific issue. is how hackers start their afternoons. We’re a part of the family. We are now and happy to opportunities. Hacker Noon @AMI accepting submissions discuss advertising &sponsorship To learn more, , , or simply, read our about page like/message us on Facebook tweet/DM @HackerNoon. If you enjoyed this story, we recommend reading our and . Until next time, don’t take the realities of the world for granted! latest tech stories trending tech stories