17

A few years ago, I wrote this in c#:

private string InternOrNot(string v)
{
    if (v == "EUREX");
        return "EUREX";
    else
        return v;
}

This method may look useless, but it's not. In fact, it dramatically decreased the memory usage of one of our servers.

This server acted as a data cache for financial data received on a Tibco Rv real-time bus. Around 20% of the overall received data was just the "EUREX" string, so the server holded references to millions of "EUREX" string objects.

By calling this method just before stocking the data, if the data to store is "EUREX", the initial reference is just discarded (and can be GCed) while I store a reference to my own unique interned "EUREX" string.

If you don't know about string Interning, you may want to look at this page.

3

Just to definitely stop the ongoing argument about string Interning, the following code demonstrates that string with equal values can have different addresses in memory.

    string a = "a";
    string ab = "ab";
    string bc = "bc";
    string c = "c";

    object abc1 = a + bc;
    object abc2 = ab + c;
    Console.WriteLine(abc1==abc2); // reference comparison returns false

    object internedabc1 = string.Intern(a + bc);
    object internedabc2 = string.Intern(ab + c);
    Console.WriteLine(internedabc1 == internedabc2); // returns true
2

Wow - that is entirely unintuitive until you explained it...then it is obvious. You just have to document that so that, a year from now, you or another developer don't look at it and think - "This is useless, I'll just take it out..."

To answer your question, I cannot think of any that looked stupid when I wrote them but lots of cases where they looked stupid when I revisited the project later. Usually, it was a head scratch and a "what was I thinking when I did that?"

2

Viewed in isolation, I suppose lots of the little functions one needs as routine 'glue' look pretty silly, e.g. Lisp

(defun identity (x) x)

or C++:

template <class T> T Construct() { return T(); }

Best I can think of off the top of my head is this from C++:

Foo::~Foo()
{
}

required for extremely subtle reasons when Foo uses an auto_ptr to hold a pimpl.