Search code examples
javascriptc#performancereusability

Code Reuse ability VS program efficiency


I'm new to programming, and In very many cases, i find myself torn whether i should copy paste code to make the program run faster, or gather methods by forcing the program to go through additional loops. I'll give you an example a bit like my current case:

solution1: (copypaste code)

button1.clickevent: saveValue1Method()
button2.clickevent: saveValue2Method()
button3.clickevent: saveValue3Method()

saveValue1Method()
{
doSomethingWithValue1()
buttonlabel.text = "you clicked a button";
doThis();
}
saveValue2Method()
{
doSomethingWithValue2()
buttonlabel.text = "you clicked a button";
doThis();
}
saveValue3Method()
{
doSomethingWithValue3()
buttonlabel.text = "you clicked a button";
doThis();
}


dosomethingwithValue1()
{
mylabel.text = 1;
}

doSomethingWithValue2()
{
mylabel.text = 2;
....
}
doSomethingWithValue3()
{
mylabel.text = 3;
....
}

solution2: (more program instructions)

button1.clickevent: saveValueMethod(1)
button1.clickevent: saveValueMethod(2)
button1.clickevent: saveValueMethod(3)

saveValueMethod(int i)
{
if (i == 1)
  {
  doSomethingWithValue(1)
  }
if (i == 2)
  {
  doSomethingWithValue(2)
  }
if (i == 3)
  {
  doSomethingWithValue(3)
  }

buttonlabel.text = "you clicked a button";
doThis();

}

doSomethingWithValue(int j)
{
if (j == 1)
   {
   mylabel.text = 1;
   ...
   }
if (j == 2)
   {
    mylabel.text = 2;
    }
if  (j == 3)
    mylabel.text = 3;
    }

Keep in mind this is just a simplified example, and doesn't necessarily make sense. In many cases i would have to loop through a lot of values, not just if 1,2 or 3.

Which concept is good coding?


Solution

  • In general you should follow the DRY principles (don't repeat yourself) and never copy blocks of code.

    Factoring your code into common functions will make your code easier to read and maintain and is unlikely to make a significant difference in performance. It is universally considered the "right" way to code.

    Even when spending serious time optimizing code for performance, it is rarely a function call that is the main cause of a slowdown and other, much more important aspects of your algorithm or task are usually a much more leveraged way to improve performance. But, please realize that in 99.99% of all code, performance of the actual bytes of code is rarely an issue. So, write your code initially for maximum clarity, reusabilty, readability and maintainability and then, only once you've proven that you actually have a performance problem somewhere and have measured exactly what is causing the problem would you consider reoptimizing your lines of code to make it run faster.