In both Python and Ruby, integers are objects. Thus, it is not a question that the “value” is an integer or a string, it can be anything. In addition, everything in both of these languages is garbage collection. There is no need to copy objects, pointers can be used internally if they are safely stored somewhere where the garbage collector collects them.
So, one solution to your problem would be the following:
class myInterpreterValue { virtual ~myInterpreterValue() {} // example of a possible member function virtual string toString() const = 0; }; class myInterpreterStringValue : public myInterpreterValue { string value; virtual string toString() const { return value; } }; class myInterpreterIntValue : public myInterpreterValue { int value; virtual string toString() const { char buf[12]; // yeah, int might be more than 32 bits. Whatever. sprintf(buf, "%d", value); return buf; } };
Then use virtual calls and dynamic_cast to enable or type check instead of comparing with the values of myInterpreterType.
The usual thing at the moment is the concern that virtual function calls and dynamic casts can be slow. Both Ruby and Python use virtual function calls everywhere. Although not virtual C ++ calls: for both languages, their “standard” implementation is in C with customizable mechanisms for polymorphism. But, in principle, there is no reason to suppose that “virtual” means “windowed performance”.
However, I expect that they both probably have some clever optimization for certain integer goals, including as loop counters. But if you currently see that most of your time is spent copying blank lines, then virtual function calls are compared almost instantly.
The real concern is how you plan to manage resources - depending on your plans for your interpreted language, garbage collection may be more of a problem than you want.
Steve jessop
source share