# When would I use boxes?

**URL:** <https://racket.discourse.group/t/when-would-i-use-boxes/813>\
**Category:** Questions & Answers\
**Created:** [March 21, 2022, 5:54am UTC](https://racket.discourse.group/t/when-would-i-use-boxes/813 "2022-03-21T05:54:14Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![alexh](https://yyz2.discourse-cdn.com/free1/user_avatar/racket.discourse.group/alexh/32/315_2.png) [@alexh](https://racket.discourse.group/u/alexh)\
**Post date:** [March 21, 2022, 11:24am UTC](https://racket.discourse.group/t/when-would-i-use-boxes/813/3 "2022-03-21T11:24:50Z")

</div>

> [@rmuller](#):
>
> but why would I want to use a box rather than a global variable?

You may be surprised to learn that `set!` is implemented using boxes. That is, code such as:

```racket
(let ([a 1])
  (set! a 2)
  (+ a 1))

```

Is translated into:

```racket
(let ([a (box 1)])
   (set-box! a 2)
   (+ (unbox a) 1))

```

You will often hear that mutable code is slower in Racket, and this is the reason why: every time you use `set!` the compiler has to box the variable and unbox it everywhere it is used -- this severely reduces the opportunities for optimizations.

As for `box-cas!` , a lot of synchronization mechanisms can be implemented using a compare-and-swap operation -- most processors provide a single machine instruction for this.

Boxes are another "under-the-hood" feature, less useful to the application programmer, but useful to language developers.

For a related discution, see [What are examples of use-cases for continuations?](https://racket.discourse.group/t/what-are-examples-of-use-cases-for-continuations/806)

Alex.

---

_[View the full topic](https://racket.discourse.group/t/when-would-i-use-boxes/813)._
