330 likes | 441 Vues
Discover effective techniques to enhance string comparison performance and execution speed in C++. This article explores the significance of optimizing string comparison by checking the first character and using built-in functions to achieve at least a 20% performance improvement. We also delve into strategies for improving application speed by validating arguments, efficient console output, and the use of shift operators to optimize mathematical operations. Learn how to pass class parameters by reference for better efficiency and readability.
E N D
Refreshing Fresher’s -Sanket Shah Freelancer:FreshBreezeSoftware 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
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
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
Sample Code class 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
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
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
Speed Difference in C E-Consultancy FZC http://www.econsultancyfzc.com 2011
Speed Difference in C++ E-Consultancy FZC http://www.econsultancyfzc.com 2011
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
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
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
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
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
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
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
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
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
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(intctr = 0; ctr < maxValue; ctr++) { summation += ctr + (a / b); } • Refined Code: float summation = 0.0; float divisionValue = a / b; for(intctr = 0; ctr < maxValue; ctr++) { summation += ctr + divisionValue; } E-Consultancy FZC http://www.econsultancyfzc.com 2011
Prefer “int” over “char” or “short” char sum_char(char a, char b) { char c; c = a + b; return c; } • Convert 2nd parameter into intby sign extension • Push sign extended parameter on stack as b • Convert 1st parameter into intby sign extension • Push sign extended parameter on stack as a • Add a and b • Cast result to char • Store result in char c • Sign extend c • Copy c into return value register and function returns to caller • caller converts from int to char • The result is stored E-Consultancy FZC http://www.econsultancyfzc.com 2011
Prefer “int” over “char” or “short” intsum_int(int a, int b) { int c; c = a + b; return c; } • Push int b on stack • Push int a on stack • Called function adds a and b • Result is stored in int c • c is copied into return value register and function returns to caller. • The called function stores the returned value E-Consultancy FZC http://www.econsultancyfzc.com 2011
“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
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++ code static address jump_table[] = { case_a, case_b, end, case_a }; unsigned int index = i - 10; if (index > 3) goto end; gotojump_table[index]; case_a: func_a(); goto end; case_b: func_b(); end: E-Consultancy FZC http://www.econsultancyfzc.com 2011
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
Don’t prefer Loop Jamming Bad Way Good Way for(i=0; i<100; i++) { stuff(); morestuff(); } for(i=0; i<100; i++) { stuff(); } for(i=0; i<100; i++) { morestuff(); } E-Consultancy FZC http://www.econsultancyfzc.com 2011
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
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
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
Thanks for being here Contact: +91 98793 56075 E-Mail: sanket.1985@gmail.com Download: http://econsultancyfzc.com/2011/10/material-download-c-c-optimization-techniques/ E-Consultancy FZC http://www.econsultancyfzc.com 2011