Solved

String.charAt(index)  Vs String.toCharArray()[index]

Posted on 2004-09-06
10
2,500 Views
Last Modified: 2008-01-09
Hello All,

Which do you think is better operation, so that it increases the performance of method

String str="Hello World";
int len=str.length();
for(int i=0;i<len;i++)
{
        char c=str.charAt(i);
}

char charArray[]=str.toCharAray();

for(int i=0;i<len;i++)
{
        char c=charArray[i];
}
0
Comment
Question by:sudhakar_koundinya
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
  • 2
  • +4
10 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 11991821
The best thing is to time it, is it not? Probably the first
0
 
LVL 5

Expert Comment

by:TrekkyLeaper
ID: 11992141
charAt is the most efficient. The toCharArray method is forced to allocate a new array to store the characters to create a disconnected copy of the array.
0
 
LVL 3

Expert Comment

by:sbockelman
ID: 11993052
Why, are you having a performance issue?

Don't optimize now!  Wait until you find out if you even need to optimize, then profile the application to see where to optimize.  The difference between the 2 alternatives shown is probably so minimal, that even the time to read my post about it was a waste of your time and client's money.

But, if it is found to be the bottleneck method, then...always let the computer tell you which way is better by timing and profiling.  And sometimes, this kind of micro-optimization won't help anyway and you'll need to completely redesign a component or algorithm to resolve the issue.

But, for curiosity sake, please let me know the timings you get for the two methods.  
I'd like to see what the difference is.  Who knows I might need to speed up some text parsing some day.
0
Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

 
LVL 6

Expert Comment

by:expertmb
ID: 11993722
char c=str.charAt(i);

is fast compared to

char charArray[]=str.toCharAray();
char c=charArray[i];

first one has array already.
second one from string you are converting to array then accessing
however after converting to array both are same.
0
 
LVL 14

Author Comment

by:sudhakar_koundinya
ID: 11993895
Hello Friends,

Thanks for ur inputs


My perception is different.

I agree for smaller strings charAt function may be fast. But when coming to big strings, I think the scenario is different. Because when I see the code for string last night I have found that toCharArray uses function System.arraycopy. We know System.arraycopy(I think it is native call) is faster.

So when we use for loop based operations on String, we are directly moving to index for char array whereas we need to call the function for charAt. So for Bigger strings calling the function multiple times may reduce the performance of the method.

What do you say??

Thanks
Sudhakar


For testing the performance I used following program


class BiggerStringTest
{
      public static void main(String[] args)
      {
            StringBuffer sb=new StringBuffer();
            int n=Integer.parseInt(args[0]);
            for(int i=0;i<n;i++)
            {
                  sb.append('*');
            }
            String str=sb.toString();
            char array[]=str.toCharArray();
            for(int j=0;j<10;j++)
            {
            
            long start=System.currentTimeMillis() ;
            for(int i=0;i<n;i++)
            {
                  if(str.charAt(i)=='A')
                  {
                        //do some thing
                  }
            }

            long end=System.currentTimeMillis() ;
            System.err.println("charAt :"+(end-start));

            
            start=System.currentTimeMillis() ;
            for(int i=0;i<n;i++)
            {
                  if(array[i]=='A')
                  {
                        //do some thing
                  }
            }

            end=System.currentTimeMillis() ;
            System.err.println("char Array : "+(end-start));

      }
      }
}

0
 
LVL 6

Assisted Solution

by:expertmb
expertmb earned 20 total points
ID: 11994003
>>So for Bigger strings calling the function multiple times may reduce the performance of the method.
accessing the array using index is faster. i said this one in one of your previous question also.

0
 
LVL 7

Assisted Solution

by:grim_toaster
grim_toaster earned 20 total points
ID: 11994265
Your performance test is biased.  To make it fairer you would need to do the array conversion more often, as in change to the following:

start=System.currentTimeMillis() ;
char array[]=str.toCharArray();
          for(int i=0;i<n;i++) {
               if(array[i]=='A')

There will be a point where the string gets so long that the processing of it will be faster to do the array conversion instead of the charAt.  Although the point will be different on every machine (and you may never get when...).  The reason for this is available if you look at the source code for the String class, the charAt method has additional boundary condition checks:

        if ((index < 0) || (index >= count)) {
            throw new StringIndexOutOfBoundsException(index);
        }

Which would be completely removed if you are accessing a local copy of the array.  However, I would be very surprised if you ever actually noticed any difference, and the figures will be very biased to what other processes are running (i.e. virus checkers).  The best bet would be to profile (I believe mentioned previously), using CPU time (as opposed to elapsed time), to get exact figures.  
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 11994545
sudhakar_koundinya, are you gonna write a book from the answers on all your performance
questions? In that case you just CAN'T use our answers.
If such a report is not based on extensive timing tests by yourself on verious platforms and
with a variety of data sets, it will be wiped away by any critic.
And if this is for your boss, he/she will surely ask a specialist to critisize it.
;JOOP!
0
 
LVL 14

Author Comment

by:sudhakar_koundinya
ID: 12005882
>>are you gonna write a book from the answers on all your performance questions?

No My Dear,

Actually we are facing severe performance problems with our current application. And also this is not at all a design Issue. Because that is the only way currently we have as we totally depend on third party API (Apache Slide and Apache HttpClient) - and that API was finalised by both our team and client team after extensive R & D only.

I am not only doing these tests, both client team and our team are doing investigation on increasing the performance of API

thanks
sudhakar
0
 
LVL 3

Accepted Solution

by:
sbockelman earned 35 total points
ID: 12006957
>> Actually we are facing severe performance problems with our current application

Have you tried something like Quest JProbe (or an open source alternative such as JMeter) to find out WHERE you should be optimizing?

I have led performance optimization efforts after-the-fact on several occasions;  I was sort of the de facto "performance tuning guy" at my last consulting company.

The effort can be very challenging; sometimes frustrating and sometimes fun.

What I have found is that it is almost always a waste of time to tune some little method here or loop there when the response times are truly horrible.  Often, the solution requires some serious creative thinking and some partial redesign.

What kind of application are you trying to tune?  
Sounds like it must be a content management application, given the use of Slide.

My last major optimization effort was for a Documentum WDK-based application.

What we found was that for some features, the API methods exposed by the framework seduced users into writing loops where methods called in the loop were making additional database calls (under the covers).  

By circumventing the DCTM API and going directly against the database, in some cases, we were able to improve performance by orders of magnitude you would not believe (one 'report' screen went from 10-15 minutes to load down to 17 seconds!)

We also found that some operations were obtaining exclusive locks in the backing database (SQL Server in that case).  Because the version of SQL Server being used was locking entire PAGES and sometimes TABLES even for read operations, we had to reconfigure the default transaction isolation level for several operations to allow for "dirty reads", which would pose no problem for our application, but may not be appropriate for yours.

Finally, poor session management and thread-safety concerns had led to some inadvertant or uncessecary synchronization with some types of requests being served serialy instead of in parallel.

SO, I would encourage you to proceed via a thorough analysis of the application's runtime characteristics.  Once you know what is slow, then you can begin to investigate the cause, and finally...possibly recommend and implement a solution.

Saving < 2 milliseconds per character-access is probably not going to solve the larger issues.

Good luck!




0

Featured Post

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
Suggested Courses

623 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question