Compares two empty strings and compares the performance of the two methods

Source: Internet
Author: User

Test the efficiency of str. isempty () and "". Equals (STR ).
Comparison times: 999999999
Str. isempty () 2735 (2.7 seconds)
"". Equals (STR) takes 10516 (10 seconds)

The difference is so big

 
Public class test4 {public static void main (string [] ARGs) {long times = 999999999; string STR = ""; long a1 = system. currenttimemillis (); For (long I = 0; I <times & Str. isempty (); I ++) {// system. out. println (Str. isempty ();} Long a2 = system. currenttimemillis (); system. out. println ("str. isempty () times: "+ (A2-A1); long b1 = system. currenttimemillis (); For (long I = 0; I <times &&"". equals (STR); I ++) {// system. out. println ("". equals (STR);} Long b2 = system. currenttimemillis (); system. out. println ("\"\". equals (STR) times: "+ (B2-B1 ));}}

Output result:

Str. isempty () times: 2735 "". Equals (STR) times: 10516

In fact, looking at the source code will soon find the problem

 
Public Boolean isempty () {return COUNT = 0 ;}

 
Public Boolean equals (Object anobject) {If (this = anobject) {return true;} If (anobject instanceof string) {string anotherstring = (string) anobject; int n = count; if (n = anotherstring. count) {char V1 [] = value; char V2 [] = anotherstring. value; int I = offset; Int J = anotherstring. offset; while (n --! = 0) {If (V1 [I ++]! = V2 [J ++]) return false;} return true ;}} return false ;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.