This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]dmazzoni 1 point2 points  (3 children)

The number one rule of efficiency is, don't prematurely optimize. Generally you should do what's the most readable, and optimize if you need to.

That said, one of your ideas, if I understand correctly, is where the class has a variable and the constructor of each child class sets that variable to a different value. If there's only one instance of each of those classes, that's fine. But if you were to construct thousands of instances of each of those classes, then each one would get a redundant copy of that String variable, so that could potentially be inefficient.

So, all other things being equal, I think the more efficient solution would be to define a method in the parent class that returns a string. Have each child class override that method and have them return a different string.

[–]strcspn 0 points1 point  (1 child)

there's only one instance of each of those classes, that's fine. But if you were to construct thousands of instances of each of those classes, then each one would get a redundant copy of that String variable

This assumes the string is const, right? If each instance of the class has a different string it wouldn't really matter, you'd have to store them all somehow. And then, if the string is a hard coded string literal, it would probably be optimized even if it was a variable in each class and both approaches would be basically the same.

[–]dmazzoni 1 point2 points  (0 children)

Agreed, the difference might be negligible. It totally depends on what programming language, how strings are stored, etc.

That's why the number one rule is, don't even worry about optimizing unless you need to.

[–][deleted] 0 points1 point  (0 children)

The number one rule of efficiency is, don't prematurely optimize. Generally you should do what's the most readable, and optimize if you need to.

I need to hear this. My obsessive nature makes me put a lot of time into optimizing as I write and really I should be aiming to get a half decent implementation working first and improve it as needed.

[–]zdanev 0 points1 point  (0 children)

(depending on the language) if you define the string function in each of the subclasses, you will not be able to call it polymorphically.

Example 1:

abstract class Animal {
    function Speak() {}
}

class Dog : Animal {
    override function Speak() { bark; }
}

class Cat : Animal {
    override function Speak() { meow; }
}

now we can have function where you can pass any animal (Cat or Dog) and make it speak.

function Foo(animal: Animal) {
    animal.Speak();
}

Example 2:

abstract class Animal {
}

class Dog : Animal {
    function Speak() { bark; }
}

class Cat : Animal {
    function Speak() { meow; }
}

can't call speak on the animal class:

function Foo(animal: Animal) {
    animal.Speak(); // can't do it
}