Our highest priority is to satisfy the customer through early and continuous delivery of valuable and working software.

Sunday, January 4, 2009

40 Tips for optimizing your php code

1. If a method can be static, declare it static. Speed improvement is by a factor of 4.

2. echo is faster than print.

3. Use echo's multiple parameters instead of string concatenation.

4. Set the maxvalue for your for-loops before and not in the loop.

5. Unset your variables to free memory, especially large arrays.

6. Avoid magic like __get, __set, __autoload

7. require_once() is expensive

8. Use full paths in includes and requires, less time spent on resolving the OS paths.

9. If you need to find out the time when the script started executing, $_SERVER[’REQUEST_TIME’] is preferred to time()

10. See if you can use strncasecmp, strpbrk and stripos instead of regex

11. str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4

12. If the function, such as string replacement function, accepts both arrays and single characters as arguments, and if your argument list is not too long, consider writing a few redundant replacement statements, passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments.

13. It's better to use switch statements than multi if, else if, statements.

14. Error suppression with @ is very slow.

15. Turn on apache's mod_deflate

16. Close your database connections when you're done with them

17. $row[’id’] is 7 times faster than $row[id]

18. Error messages are expensive

19. Do not use functions inside of for loop, such as for ($x=0; $x < count($array); $x) The count() function gets called each time.

20. Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function.

21. Incrementing a global variable is 2 times slow than a local var.

22. Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable.

23. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.

24. Just declaring a global variable without using it in a function also slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists.

25. Method invocation appears to be independent of the number of methods defined in the class because I added 10 more methods to the test class (before and after the test method) with no change in performance.

26. Methods in derived classes run faster than ones defined in the base class.

27. A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar++ operations. A similar method call is of course about 15 $localvar++ operations.

28. Surrounding your string by ' instead of " will make things interpret a little faster since php looks for variables inside "..." but not inside '...'. Of course you can only do this when you don't need to have variables in the string.

29. When echoing strings it's faster to separate them by comma instead of dot. Note: This only works with echo, which is a function that can take several strings as arguments.

30. A PHP script will be served at least 2-10 times slower than a static HTML page by Apache. Try to use more static HTML pages and fewer scripts.

31. Your PHP scripts are recompiled every time unless the scripts are cached. Install a PHP caching product to typically increase performance by 25-100% by removing compile times.

32. Cache as much as possible. Use memcached - memcached is a high-performance memory object caching system intended to speed up dynamic web applications by alleviating database load. OP code caches are useful so that your script does not have to be compiled on every request

33. When working with strings and you need to check that the string is either of a certain length you'd understandably would want to use the strlen() function. This function is pretty quick since it's operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP). However because strlen() is a function it is still somewhat slow because the function call requires several operations such as lowercase & hashtable lookup followed by the execution of said function. In some instance you can improve the speed of your code by using an isset() trick.

Ex.
if (strlen($foo) < 5) { echo "Foo is too short"; }
vs.
if (!isset($foo{5})) { echo "Foo is too short"; }

Calling isset() happens to be faster then strlen() because unlike strlen(), isset() is a language construct and not a function meaning that it's execution does not require function lookups and lowercase. This means you have virtually no overhead on top of the actual code that determines the string's length.

34. When incrementing or decrementing the value of the variable $i++ happens to be a tad slower then ++$i. This is something PHP specific and does not apply to other languages, so don't go modifying your C or Java code thinking it'll suddenly become faster, it won't. ++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While pre-incrementation increases the original value directly. This is one of the optimization that opcode optimized like Zend's PHP optimizer. It is a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer.

35. Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory.

36. Do not implement every data structure as a class, arrays are useful, too

37. Don't split methods too much, think, which code you will really re-use

38. You can always split the code of a method later, when needed

39. Make use of the countless predefined functions

40. If you have very time consuming functions in your code, consider writing them as C extensions

41. Profile your code. A profiler shows you, which parts of your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you the bottlenecks in overview

42. mod_gzip which is available as an Apache module compresses your data on the fly and can reduce the data to transfer up to 80%

43. Excellent Article about optimizing php by John Lim

Monday, June 2, 2008

Debugbar - firebug for IE, IETester, Companion.JS - Javascript debugger for IE

Lots of web developers love Firebug in FF, but it's hard to debug anything in IE or No proper debugger tool is there for IE. Today I came across a debugger tool for IE - Debugbar

It's an Internet Explorer plug-in that brings you new powerful features.
- DOM Inspector: View DOM Tree and modify tags attributes and css attributes on the fly to test your page
- HTTP Inspector: View HTTP/S request to check cookies, GET and POST parameters, view server info
- Javascript Inspector and Javascript Console: View javascript functions for easier debugging, see Javascript and AJAX code
- HTML Validator: Validate HTML code to correct and optimize your code and html size of your page
- And many more features: See page cookies, get pixel color on a page, make a page screenshot...

In DebugBar 5.0.2 BETA you will find...
- Greatly improved DOM tab : for each element, get the applied styles, computed style, layout and attributes


- Fully unicode, support for international characters



Download Here



Another good tool for IE is IETester
IETester is a free web browser that allows you to have the rendering and javascript engines of IE8 beta 1, IE7 IE 6 and IE5.5 on Vista and XP, as well as the installed IE in the same process.


Download Here



Companion.JS (pronounced Companion dot JS or CJS) is a Javascript debugger for IE.
- Detailled javascript error reporting (call stack and real file name where the error occured).
- "Firebug"-like Console API feature.
- Javascript console feature useful to inspect javascript objects at runtime.
- A toolbar icon to open the Companion.JS panel.



Download Here

Sunday, June 1, 2008

Startup City Bangalore - Summary of various talks


Last Saturday (24th May), I attended the startup city at NIMHANS convention center, Bangalore. The event was organized by The Smart Techie Magazine & sponsored by Sun, Amazon, Microsoft, Yahoo and a host of other companies. The idea was to promote the start up culture, share experiences, network with VCs and see cool startups in Bangalore who were demoing their products.
http://www.thesmarttechie.com/startupcity/Exhibitors.php

I have summarized some of the points below.



The first talk was by Ashish Gupta from Helion Venture Capital firm. He is a co-founder of Helion & has invested in over 35 companies in the U.S. and in India.

He talked about how to start a startup, the various phases that a startup goes through.

Summary of his talk:-
* Startup Risks
- You have to work hard to deliver what you have committed
- What do you want?
(1) Talent from brand? OR
(2) Expertise required for the work need to be done?

* Remember - money, people & information can move at any time.

* Growth of startup is like growth of a child.
- In first 6 months, you need to learn lots of things.
- Next 12 months are execution of what you have planned.
- In next 2 years, you will be mature enough to play on ground.

* Behavior change
- Change expense pattern
- Next level CEO
- Need to change process
- Need to introduce new technology
- Need to change business or pricing model

* ASP business model
http://en.wikipedia.org/wiki/Application_service_provider

* Think
- What company would need a year from today?
- Measure stuffs

* Rules of thumb
- Focus on the customer or issue.
e.g. If a glass is dropped by someone, then don't waste your time to figure out, who broke the glass, what's the reason behind it. The key task here is: How fast you can clear the floor? Then you can check how to avoid this condition in future?
- Focus on continuous improvement
- Intellectual honesty
- Results matter - only for measuring



The second talk was by some executive of Sun about the startup essentials program. Basically, the talk was for marketing of their program. The Sun Startup Essentials program is designed specifically to help startups get off the ground rapidly and at lower cost. Find out more @ http://in.sun.com/startup



Then there was a panel discussion on Consumers and Business Marketing in High Technology. The panel consisted of members from Nokia, Microsoft, Amazon and IIMB. The talk was mentored by Dr. Y.L.R. Moorthi, Professor (Marketing), IIM Bangalore.

Summary of this discussion:-

- Find the opportunity or idea
- Make it global
- Pre-evaluation of product i.e. whether idea is right or not?
- Acquiring users for your product. Engage / Retain the users
- Stay tuned with current technology & Current market
- How do you go out, reach to people & make money? i.e. How to monetize that idea?
e.g. zara supply chain management - http://hbswk.hbs.edu/archive/4652.html
- If you think like startup, you have an opportunity for marketing. i.e. if you are startup, you can approach other than traditional way for marketing.
e.g. (1) Kinetics's Dancing Baby Marketing Strategy (2) Cello's Hello Marketing Strategy
- Build strong word of mouth
- Create partners / channels
- Check, if product changes, what will happen to brand?
- You are not the only one developing a product in an area. There will be many startups doing the same thing. So implementation is as important as the idea itself.

- Start with market; don't start with product (Paul Murphy - Director of innovation, Microsoft India)

- Challenges faced by a startup to market its products.
e.g. Nokia is a 160 year old company and still it faces many of the challenges a startup faces. Many of the problems faced by a startup and a big company are same. In a big company, you came upon this brilliant idea for a new product or feature. You will make a prototype; take it to the senior technical people to get it approved. Then you will go to management saying that this has a market value and try to convince them and once approved, get the funds from the higher management to develop the product and finally sell it to the consumers. If at any point in time, it does not work, you are back to square one. In case of a startup, the techie thinks of the product, makes a prototype, goes to a VC and tries to sell the idea. Many VC's will reject him and may be he will be able to convince a VC finally. Then with the money, he make the product and then sell it. If it does not sell or he hits a failure in-between, he is back to his original position. Hence, the problems are same, just that in the case of the startup, it’s your own money, and in case of the big company, its the company's money and hence you have security and safety to fall back on.

In case of Failure:
- What are the factors for failure?
- How is failure rewarded?



Fourth talk was by Jinesh Varia from Amazon about cloud computing and the Amazon EC2 initiative. http://aws.amazon.com/ec2

Summary of his talk:-

* Lots of factors are there between an idea and actual product.
- Hardware cost
- S/w cost
- Maintenance
- load balance
- scaling
- Utilization
- Idle m/c's
- Bandwidth etc.

* What is changed in last few years?
- Bandwidth is getting abundant & cheap
- Hardware is become ubiquitous

* Think for an idea & left other things to cloud computing.

* Scaling problem in startup.i.e. if user base increase your product should be scaled accordingly.
e.g.
(1) Animoto who was running on 50 machines and then within 3 days of launching a facebook application, they needed 500 machines. Such sort of scalability could be got only by such cloud initiatives as a startup simply doesn't have the money to but so much hardware so quickly.

(2) OOYALA - server less startup

(3) New your times prorated supercomputing
http://open.nytimes.com/2007/11/01/self-service-prorated-super-computing-fun/
http://open.blogs.nytimes.com/tag/hadoop/

* Embrace the uncertainty
- Acquire resources on demand
- Release resources when no need
- Use only what you need

* Growth with demand



Fifth talk was by R.K. Mishra. This was probably the most inspiring talk. He started of telling us about his school, college (IIT Kanpur) and then he went to Japan for higher studies and how he started his venture out there. Then he came back to India and started working for a MNC who's India operations he was heading and after two years he bought out the company. He also started traveljini.com in 1999 which was the first online travel portal in India which he sold to ICICI Ventures. He retired at 40 and started getting involved with public work. His talk was filled with great examples, and positive attitude towards solving many of the problems facing our country.



Second half was a CEO's conclave. The panel consisted of Sharad Sharma, head of Yahoo India, Kris Gopalakrishnan, CEO of Infosys and heads of Dell India and Intel India. It was an interesting talk which discussed problems facing the Indian startup scene and about scaling a startup.

Summary of this discussion:-
* How startup is different from RnD Company?
- Idea should create value
- Team
- Capital
- Execution

* New markets (India, China etc) & New technologies

* Keep an eye on customer needs

* Enhance the experience through co-creation (e.g. Google code platform)

* SAAS model: http://en.wikipedia.org/wiki/Software_as_a_Service

* Problems in India (Build your products to resolve these issues)
- Health service
- Energy cost
- Education
- Food

* Next emerging opportunities in India
- SAAS + mobile
- Solve consumer problem in India
- Information analytics i.e. intelligent mashing
- Make metadata free

* Imagination + intelligent is no always Innovation

* Radical change required?
e.g. Are you ready to give up control at the right point in time? i.e. Are you ready to hire a CEO from outside in order to let the company grow ?

* Opportunity is growing faster in India

* How to scale revenue?

* Create new leaders

Friday, April 18, 2008

How to mount external ntfs USB in RHEL?

Follow the steps to mount external ntfs USB in RHEL or in any linux system.

Get your kernel version: uname -r
2.6.9-42.ELsmp (For my RHEL)
.................
Install the package downloaded according to your kernel version
http://rpmfind.net/linux/sourceforge/l/li/linux-ntfs/
rpm -ivh kernel-module-ntfs-2.6.9-42.ELsmp-2.1.20-0.rr.10.0.i686.rpm
.................
/sbin/modprobe ntfs (as root)
.................
cat /proc/filesystems
.................
Check volume names of your USB Drive.
cat /etc/fstab
..................
Mount external ntfs USB
sudo mount /dev/sdb1 /mnt/usb/ -t ntfs -r -o umask=0222
..................
Unmount external ntfs USB
sudo umount /dev/sdb1 /mnt/usb/

You r done!

Monday, March 10, 2008

Export data to a CSV file using MySQL command prompt


SELECT tableColumnName1, tableColumnName2
INTO OUTFILE '/path/to/file/data.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM tableName;

Access Denied

Even if you have been granted the SELECT privilege, you will still need to be granted the FILE privilege, or else access will be denied. Some architects will only grant this privilege to the root user. Another reason that you might receive an access denied message, is because the directory where you are trying to save the CSV file is not writable.

In order to prevent a user from accidentally overwriting an important system file (like etc/passwd), you will be unable to save over a file that already exists on the server.