samedi 15 mai 2021

Polymorphism vs conditions time consumption test

for example I have the following case

class Person:
    def __init__(self, language):
        self.lang = language

    def greetings(self):
        if self.lang == 'English':
            return "Hello"
        elif self.lang == 'Spanish':
            return 'Hola'
        elif self.lang == 'German':
            return 'Hallo'
        elif self.lang == 'Russian':
            return 'Привет'

We can optimize it with polymorphism

class Russian:
    def greetings(self):
        return 'Привет'

class English:
    def greetings(self):
        return "Hello"

class German:
    def greetings(self):
        return "Hallo"

class Spanish:
    def greetings(self):
        return "Hallo"

Most answers for related questions tells that the second way is a better choice because or code maintainability, functionality extension etc.

But I haven't found answers about time consumption. So, I have a question. Which option is faster? Particularly for this case and for cases with more complex if/else blocks.

Aucun commentaire:

Enregistrer un commentaire