Recently I’ve been working through some optimizations to some code and realized that there are alot of programmers who don’t know some programming best practices. There is alot to do with the performance of a program with how the programmer wrote it. Here are some things to concider:
- When looping through your code, do not include a function in a for loop as the max value. Set the max value outside of the loop and assign the value to a variable.
Javascript Example
var l = document.getElementsByTagName('TD'); for (i=0; i<l; i++) { //do something }
- When searching through a string, if you know the data your looking for is near the end, use a function which searches backwards instead of forwards.
vb6 example
If NOT InStrRev("how now brown cow", "cow") = vbNullString Then 'do something End If
- When looping or iterating through an array, make sure you exit the loop if you have completed the necessary task.
php example
$arr = array('a', 'b', 'c', 'd', 'e', 'f', 'g'); foreach($arr as $a) { if ($a == 'd') { //do something break; } }
- If possible, use string searching functions instead of regular expression functions.
- Always close database connections, or any kind of stream connection when you are finished with them.
python example
conn = MySQLdb.connect(host="localhost", user="username", passwd="password", db="database") cursor = conn.cursor () cursor.execute ("SELCT column1, column2 FROM tablename") #do something cursor.close () conn.close ()
- Do not use the wildcard ‘*’ in your sql queries unless you really need to pull ALL the columns
- Use ’switch’ statements vs multiple if else statements when possible
perl example
switch ($var) { case 1 {#do something} case 2 {#do something} case 3 {#do something} }
- Avoid creating extra variables.
c++ example
double x;
x = 10;
//instead of assigning the value to another variable such as 'y'
x = x + 20;
- Instantiate multiple variables in one statement
c++ example
int i, j;
//vs
int i;
int j;
- Destroy all variables (especially array variables) if you are finished using them.
php example
$arr = array("uno", "dos", "tres"); //do something with array unset($arr);
- In any strongly typed language, KNOW YOUR TYPES. Many times there are types that are used for functionality that take up more bytes than necessary.
C# example
// use: int i = 100; //instead of: long i = 100;
This is a very short list but I will add more later. If you have any suggestions don"t hesitate to contact me.
Related Links
Leave a Reply
You must be logged in to post a comment.
