Reducing unncessary string copying

Hi folks,

I've observed in many C applications, often compile-time defined
data like strings are copied unnecessarily.

For example, if you pass names to certain objects (eg. opening a
file, creating a window, etc) that will never change of disappear
during the process' lifetime (eg. compiled-in), those strings
dont need to be copied.

Now the big question becomes: how to decide this ?

I'm currently experimenting with a new string reference datatype
that has an extra bit which tells whether the string is static.
Essentially a struct consisting of the char* pointer and an
extra byte for the flag. That struct then will be used instead
of the const char* pointers. A few inline functions handle the
conversion from/to normal const char* and on-demand copying.

Just some theoretical example:

Some function

    FOO* create_foo(const char* name)

now becomes

    FOO* create_foo(GCStr name)

and the call now would be

    create_foo(G_CSTR_STATIC("hello world"));

in case we dont have an "static" string, but something with
limited lifetime, it could look like this:


Inside create_foo() we'll then replace g_strdup() by some
G_CSTR_COPY() and g_free() by G_CSTR_FREE(). These functions
will know whether the string has to be copied/free'd.

Let's just leave the question of API-compatibility aside,
what do you think about this idea ?

 Enrico Weigelt, metux IT service --

 phone:  +49 36207 519931  email: weigelt metux de
 mobile: +49 151 27565287  icq:   210169427         skype: nekrad666
 Embedded-Linux / Portierung / Opensource-QM / Verteilte Systeme

[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]