Top Banner
Refreshing Fresher’s -Sanket Shah Freelancer: FreshBreeze Software Consultancy Services ( FreshBreeze.co.in ) Corporate Trainer: E-Consultancy FZC (EConsultancyFZC.com ) Blogger: http://www.sanket-shah.com E-Consultancy FZC http://www.econsultancyfzc.com 2011
33

Refreshing Fresher’s

Feb 22, 2016

Download

Documents

Lori

Refreshing Fresher’s. -Sanket Shah Freelancer: Fresh Breeze Software Consultancy Services ( FreshBreeze.co.in ) Corporate Trainer: E-Consultancy FZC ( EConsultancyFZC.com ) Blogger: http://www.sanket-shah.com. E-Consultancy FZC http://www.econsultancyfzc.com 2011. - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Refreshing Fresher’s

Refreshing Fresher’s

-Sanket ShahFreelancer: FreshBreeze Software Consultancy Services (FreshBreeze.co.in)Corporate Trainer: E-Consultancy FZC (EConsultancyFZC.com)Blogger: http://www.sanket-shah.com

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 2: Refreshing Fresher’s

Improving String Comparison• Our belief:

• “Don’t re-invent the wheel”

• To compare string, naturally and with basic instinct, we go for in-built function – strcmp()

• But…• What about performance? Can we increase?• Let’s say I’ve two strings as:• String1 = “sanket”• String2 = “Sanket”

• The best way to improve performance – Check first character and if they are same, then only proceed.

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 3: Refreshing Fresher’s

Improving String Comparison• The optimized way can be written as:• return (*s != *t ? *s - *t : strcmp(s, t));

• Execution benefit? • AT LEAST 20% (MIN VALUE) AS TESTED ON VARIOUS

COMPILERS !!!

• Sample Code: ModFunc.c

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 4: Refreshing Fresher’s

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 5: Refreshing Fresher’s

Sample Codeclass A{

int x, y, z;public:

A();};

class B{

A a;int p, q, r;// Other Variables...

public:B() {}

};

A::A() {x = 0; y = 0; z = 0;}

• Whether class A has any constructor?

• Whether class B has any constructor?

• Will class B invoke class A’s constructor?

• What is the price of Object of class A?

• What is the price of Object of class B?

• Is constructor body empty for class B?

• What effect is there at runtime?

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 6: Refreshing Fresher’s

Answers to Questions…• Whether class A has any constructor?

• Whether class B has any constructor?

• Will class B invoke class A’s constructor?

• What is the price of Object of class A?

• What is the price of Object of class B?

• Is constructor body empty for class B?

• What effect is there at runtime?

• Yes

• Yes

• Yes

• 6 bytes

• Size of variables of B + 6 bytes

• No. Invokes constructor of A. Such as: B::B() {a.A::A();}

• Higher the objects of B, higher the objects of A will be created internally

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 7: Refreshing Fresher’s

Optimizing Execution• Speed of application can be improved on functions that

execute frequently.

• The key is to validate data / arguments first and the perform (possibly) tedious jobs.

• In C++, create objects / variables once all checks have passed.

• Sample Code:• FactImpr.c• FactImpr.cpp

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 8: Refreshing Fresher’s

Speed Difference in C

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 9: Refreshing Fresher’s

Speed Difference in C++

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 10: Refreshing Fresher’s

Optimizing Console Output• On UNIX:• endl > string > character

• On Windows:• string > character > endl

• But one thing is always same:• string > character

• Reason being in “character”, we deal with only a single value, whereas in “string”, we deal with array (“\n” + Terminating NULL)

• Sample Program:• NewLine.cpp

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 11: Refreshing Fresher’s

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 12: Refreshing Fresher’s

Optimization using shift operators• Always prefer shift operators if multiplication or division is in

power of 2• Shift operators only work on integers• Instead of calculations using Registers and ALU, operation is

performed directly by shifting bit in Holding Register• Equivalence:• x << y ó x * 2y• x >> y ó x / 2y

• Sample Code:• BitShift.cpp

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 13: Refreshing Fresher’s

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 14: Refreshing Fresher’s

Optimizing Mathematical Operations• a*b + a*c = a*(b+c)• Gets rid of one multiplication

• b/a + c/a = (1/a)*(b+c)• Replacing two divisions by a division and a multiplication. On

every platform, divisions are slower than multiplications, so this rewrite will provide a speed improvement

• (a || b ) && c ) = c && ( a || b )• C++ standard requires lazy evaluation.• Whenever “c” happens to be false, in the first case ( a || b ) has

to be evaluated, whereas in the second case, it can be skipped as the entire expression can never evaluate to true.

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 15: Refreshing Fresher’s

Pass Class Parameters by Reference• Pass by Value:• Invokes copy constructor

• Pass by Reference:• “dereference” instruction

• Beneficial, especially when classes use string data types

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 16: Refreshing Fresher’s

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 17: Refreshing Fresher’s

Use Initialization over Assignment• Initialize object at the moment it is declared

• Initializing object invokes copy constructor

• Defining and assigning invokes default constructor and assignment operator

• Postpone declaration until you can do an initialization

• Saves CPU Cycles also

• Improves Readability

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 18: Refreshing Fresher’s

Return Value Optimization• Original Code:

complex<double> Mult(const complex<double>& a, const complex<double>& b){

complex<double> c;double i = (a.real() * b.imag()) + (a.imag() * b.real());double r = (a.real() * b.real()) - (a.imag() * b.imag());c.imag(i);c.real(r);return (c);

}

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 19: Refreshing Fresher’s

Return Value Optimization• First Refinement:

complex<double> Mult(const complex<double>& a, const complex<double>& b){

complex<double> c((a.real() * b.real()) - (a.imag() * b.imag()), (a.real() * b.imag()) + (a.imag() * b.real()));

return (c);}

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 20: Refreshing Fresher’s

Return Value Optimization• Second Refinement:

complex<double> Mult(const complex<double>& a, const complex<double>& b){

return (complex<double>((a.real() * b.real()) + (a.imag() * b.imag()),

(a.real() * b.imag()) - (a.imag() * b.real())));}

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 21: Refreshing Fresher’s

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 22: Refreshing Fresher’s

Minimize Local Variables• Less Local Variables:• Compiler can probably fit them easily in registers• No / less overhead of setting up and restoring frame pointer

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 23: Refreshing Fresher’s

Avoid Unnecessary Looping Calculations• Do not perform repetitive tasks in loops for which value will

not change or the value of part of expression can be derived as a fixed constant.

• Original Code:float summation = 0.0;for(int ctr = 0; ctr < maxValue; ctr++){

summation += ctr + (a / b);}

• Refined Code:float summation = 0.0;float divisionValue = a / b;for(int ctr = 0; ctr < maxValue; ctr++){

summation += ctr + divisionValue;}

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 24: Refreshing Fresher’s

Prefer “int” over “char” or “short”

char sum_char(char a, char b){

char c;c = a + b;return c;

}

1. Convert 2nd parameter into int by sign extension

2. Push sign extended parameter on stack as b

3. Convert 1st parameter into int by sign extension

4. Push sign extended parameter on stack as a

5. Add a and b6. Cast result to char7. Store result in char c8. Sign extend c9. Copy c into return value register

and function returns to caller10. caller converts from int to char11. The result is stored

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 25: Refreshing Fresher’s

Prefer “int” over “char” or “short”

int sum_int(int a, int b){

int c;c = a + b;return c;

}

1. Push int b on stack2. Push int a on stack3. Called function adds a and b4. Result is stored in int c5. c is copied into return value register

and function returns to caller.6. The called function stores the

returned value

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 26: Refreshing Fresher’s

“if…[else if]…else” vs “switch…case”• Use switch case:• Comparison with fixed set of constant values

• Use if statements:• Comparison with Sequence

• If there are multiple cases associated with single action, do not repeat statements, rather use fallback mechanism. This performs only 1 computed “goto” instead of sequence of branches (Refer to next slide).

• put the most typical cases before• If compiler does not use jump-table, cases are evaluated in order of

appearance; therefore, fewer comparisons are performed for more frequent cases.

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 27: Refreshing Fresher’s

Sample “switch…case” to Pseudo Machine Code

switch (i){

case 10:case 13:

func_a();break;

case 11:func_b();break;

}

// N.B.: This is not C++ codestatic address jump_table[] = { case_a, case_b, end, case_a };

unsigned int index = i - 10;

if (index > 3) goto end;

goto jump_table[index];

case_a: func_a(); goto end;

case_b: func_b();

end:

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 28: Refreshing Fresher’s

Making “for…” loop fast• for( i=0; i<10; i++){ ... }• Slowest

• for( i=10; i--; ) { ... }• Fastest, if we don’t care for lower bound

• for(i=10; i; i--){}• Faster as comparison is made with only zero value• Same as for(i=10; i!=0; i--){}

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 29: Refreshing Fresher’s

Don’t prefer Loop Jamming

Bad Wayfor(i=0; i<100; i++){

stuff();}

for(i=0; i<100; i++){

morestuff();}

Good Wayfor(i=0; i<100; i++){

stuff();morestuff();

}

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 30: Refreshing Fresher’s

Declare Variables in innermost scope• Better Performance• Less Overhead of creating / destroying object• Higher memory remains available• Objects not created unnecessarily when the conditions fail• Memory marked for deletion when scope is closed

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 31: Refreshing Fresher’s

Other Ideas• Java – Use StringBuffer if multiple string manipulation

operations are there• .NET – User StringBuilder (same as Java Case)• Stay away from Virtual Functions as far as possible as that

involves lot of stack operations• Use Properties instead of fields if validation(s) needs to be

performed. E.g. – Age• Use finally block wisely • Do not import unnecessary namespaces• Break large classes in multiple files (Partial Classes in .NET)• Use Double Buffer while updating UI through Threads

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 32: Refreshing Fresher’s

Other Ideas• Use Threading to prevent blocking of application UI when

performing large operations• Always handle Exceptions at the closest point of occurrence as

they’ll bubble up if not handled properly• Exceptions always consume more resources• Try to stay away from traditional COM Objects

E-Consultancy FZC http://www.econsultancyfzc.com 2011

Page 33: Refreshing Fresher’s

Thanks for being here Contact: +91 98793 56075E-Mail: [email protected]: http://econsultancyfzc.com/2011/10/material-download-c-c-optimization-techniques/

E-Consultancy FZC http://www.econsultancyfzc.com 2011