To copy or not to copy, that is the question.

Carl Sassenrath, CTO
REBOL Technologies
9-Apr-2006 18:03 GMT

Article #0006
Main page || Index || Prior Article [0005] || Next Article [0007] || 21 Comments || Send feedback

Ok, this subject is both deep and broad, but I want to get you started thinking about it...

One issue that we need to settle very soon is the issue of when to copy and when not to copy REBOL series (strings, blocks, etc.). This issue permates all of REBOL, and it is important because the copy/non-copy rules must be firmly in your mind while you program in REBOL.

For example, there is the simple case of when you use literal strings in REBOL, such as in a function:

fun: func [str] [append "example " str]

Most of us recognize this issue. The first time we call the function:

print fun "test"
example test

and, the second time:

print fun "this"
example testthis

The literal string is being modified. To prevent this you must write:

fun: func [str] [append copy "example " str]

This is one of the first things a beginner learns - and, usually from being burned by it.

But, the issue gets deeper really quickly because it applies to all REBOL series including blocks, parens, filenames, URLs, etc.

For example, when you create an object in this manner:

obj-body: [a: 10 b: [print a]]
obj1: make object! obj-body
obj2: make object! obj-body

You get into the issue of whether the obj-body block should be copied before it is bound (binding the object fields variables). The original obj-body is being modified by make. If you don't know that, you may get surprised. Surprise!

The same can be said about function specs, bodies, etc. etc.

So, this is an issue that is worth revisiting in REBOL 3.0. There are two opposing REBOL principles at work:

  1. Simplicity: we want to minimize the side effects in normal code. Good for beginners and probably good for us experts too.

  2. Optimization: minimize memory and maximize performance. If we have to copy strings and blocks in a lot of places, it takes time and memory to do so.

So, there are some issues that you should think about if you are deeply into REBOL programming. We need a stated solution. It can be any of:

  1. Do nothing. Leave it like it was.

  2. Change it where it is most appropriate and optimal.

  3. Change it everywhere and ignore the extra memory and lost performance.

So, there's something to consider next time you relax at the pub, smoke your pipe in your easy chair, or scale the local mountain range. And, I invite you to share your insights with the group, either here in the comment section here or via your own blog or web pages.


Updated 13-Jun-2024 - Edit - Copyright REBOL Technologies -