You've Been Using Java Strings WRONG All This Time!

แชร์
ฝัง
  • เผยแพร่เมื่อ 23 ธ.ค. 2024

ความคิดเห็น • 155

  • @omer_usta
    @omer_usta ปีที่แล้ว +197

    Dont forget one important note that StringBuilder is not thread-safe , it should not be used in a multithreaded environment without proper synchronization. If you need to use StringBuilder in a multithreaded environment, you should use StringBuffer instead, which is a thread-safe alternative

    • @GFunkEra1992
      @GFunkEra1992 ปีที่แล้ว +2

      yes, but using multithreading is very specific. Not all companies uses it.

    • @RobertSaulnier
      @RobertSaulnier ปีที่แล้ว +11

      I can't think of a single use case where a StringBuffer makes sense, even in a multithreaded environment. Threads will most likely call append multiple times so what will the output look like? Garbage

    • @adityabhale1858
      @adityabhale1858 ปีที่แล้ว

      Thanks Omer for the information 👍

    • @vishwajitswami6450
      @vishwajitswami6450 ปีที่แล้ว

      Thanks Omer , Nice explanation

    • @kishoreramana1
      @kishoreramana1 ปีที่แล้ว

      @@GFunkEra1992 there is no impact of multithreading for local vraibles

  • @V4dk4n
    @V4dk4n ปีที่แล้ว +19

    We were taught at school not to use strings, but stringbuilders for concat, for this very reason, I just never thought that the difference would be this big, thanks for the video!

  • @rpdemo
    @rpdemo ปีที่แล้ว +10

    What I most like on your videos is your sense of humor, making learning into a funny thing.
    Nice work man!

  • @gorandev
    @gorandev ปีที่แล้ว +6

    At 4:22 there is no need to invoke "toString()" on the StringBuilder instance. If you look under the hood, "String.valueOf(sb)" calls the "toString()" method for you. That is why it gets greyed out in your IDE, it is redundant.

  • @ghostcoderz
    @ghostcoderz ปีที่แล้ว +33

    Great video... Thanks for making this video. Nobody tells these small things that make a big difference in production.

    • @DevToolsMadeSimple
      @DevToolsMadeSimple ปีที่แล้ว

      True

    • @z00lus
      @z00lus ปีที่แล้ว +4

      Its classic. Read Effective Java by Joshua Bloch. Item 63 about performance of string concatenation. And in general whole book is very good.

  • @martins2246
    @martins2246 ปีที่แล้ว +6

    How I code for real, and how I code in interviews are different. The interview test is high pressure, and challenging. I like to stick with the old += and then mention "I know there is an optimization for this if we concat a lot of strings in a loop..." and away we go. I feel the same way about Autoboxing. I like to keep things easier to flow with under those conditions and then mention "I can optimize these Autoboxes later..." and it usually gets a grunt that sounds positive.

  • @bkaaron3728
    @bkaaron3728 ปีที่แล้ว +2

    You are a great teacher. I have improved a lot as a back end developer. Just from your videos. So many Java developers here in Uganda use your content, its so easy to understand. I got to understand security from your videos

  • @CottidaeSEA
    @CottidaeSEA ปีที่แล้ว +4

    Whether to use StringBuilder/StringBuffer (StringBuffer is thread safe) or just do += or similar depends primarily on many times you're doing it. If it's just one or two times you might as well use += because the performance drops are negligible.

  • @hardikpanchal9726
    @hardikpanchal9726 ปีที่แล้ว +3

    Hi Amigo,
    That's for the detailed explanation. These are some small mistake which youngsters are making special in production environment which sometimes creates large delaye in applications execution. It was very helpful.

    • @Markus-fw4px
      @Markus-fw4px ปีที่แล้ว

      But why? If you know better, why don't you code it the proper way right away? It doesn't seem to be more effort.

  • @gavipk
    @gavipk ปีที่แล้ว

    what's in the stringbuilder? an arrayList that holds chars that assembles a string all in one object? how would someone go about crafting their own stringbuilder in Java?

  • @awabalbaalbaky3508
    @awabalbaalbaky3508 ปีที่แล้ว +1

    I always use StringBuilder but you just said in the beginning that the compiler optimize it to use StringBuilder automatically, or that's different?

  • @ontaduchocon
    @ontaduchocon ปีที่แล้ว +2

    Please explain the advantages of LocalDataTime with java.util.Data or Calendar . why choose LocalDateTime i think Data or Calendar have some bugs , Right ?

  • @misaelpereira9679
    @misaelpereira9679 ปีที่แล้ว +2

    Awesome learning! I could not imagine the performance impact!

  • @Edzward
    @Edzward ปีที่แล้ว

    Very insightful! I remember seeing that a long time ago while learning Java.
    The most probably reason is because Strings are actually a Array of Chars.

  • @reddish98
    @reddish98 ปีที่แล้ว +4

    I agree with the lesson of this video, although I´d like to point out that in real usage the slow vs fast methods would not have that much of a performance difference. I can't think of any scenarios where the same string would be appended to 1 million times. Assuming that each string is only appended to 10s or maybe 100s of times before a brand new one is created, using a StringBuilder would still be faster but not near to the performance gains shown in this example. Nevertheless a great point and video

    • @RzariRzari
      @RzariRzari ปีที่แล้ว +2

      In systems which generate files, reports etc. for example ERP systems, appending string multiple times is pretty frequent functionality

    • @reddish98
      @reddish98 ปีที่แล้ว

      @@RzariRzari I really don't know a lot about those types of systems but I´d be surprised if they append the same string millions of times without writing it to a file (and clearing the string)

    • @simonfarre4907
      @simonfarre4907 ปีที่แล้ว

      This is bad advice. I don't use Java myself, at work or at home, because, hey, it's just not great - but that's beside the point - why this is bad advice is because String is an immutable type. Writing code like that, informs the human on the other side that you're doing some form of mutation. You're essentially making a logic or reasoning error.
      StringBuilder (although a _terrible_ name, Java should have just went with what other languages do, and make a String class that is not immutable and a StringRef that is) should be used regardless. Because that signals that "hey, I'm doing some mutation here". Secondly
      s += "foo"
      using an immutable type comes with another problem (in a single threaded context) - you're throwing away the reference to the prior string. That means now, the GC has to perform extra work. Whether or not you are "appending" a million times or a hundred times, you are creating objects, fragmenting the heap and adding additional work for the GC. This _is_ costly. Particularly since GC's, in 2023 aren't great, they never will be great, because that's just a fact of life in that problem domain (I'm not saying GC's should never be used, I'm just saying they come with overhead).
      So it's not just about performance, although that *certainly* is the most important part, but it's also about the logic of the code. Strings are immutable. And when you do += you have not just created a new string, you have discarded the reference to the old one. That is _not_ the intention of appending, and most likely not what the programmer intended either, although it is explicitly what happens.

    • @RobertSaulnier
      @RobertSaulnier ปีที่แล้ว

      @@simonfarre4907 your obviously haven't kept up with GC performance. ZGC runs full gcs in less than a millisecond with Tera bytes of heap

    • @simonfarre4907
      @simonfarre4907 ปีที่แล้ว

      @@RobertSaulnier Do you know what trade offs ZGC has made to be able to be faster? Because there are no silver bullet GC's. GCs are a tool we use to make certain development more ergonomic, but it always comes at the cost of performance. Yes, GC's are faster today than they were 10-15 years ago, but guess what, so are computers.
      Garbage collection come with inherent constraints, it's part of the trade off game we play. But GC is always, always less performant.

  • @nightfox6738
    @nightfox6738 ปีที่แล้ว

    I'm curious why Java's String class doesn't do append behind the scenes for +=. That seems like a bit of a serious oversight.

  • @aryangholamlou
    @aryangholamlou ปีที่แล้ว +2

    Hi, Amigo.
    What's your IntelliJ theme that your folders and subfolders like that ?
    Thanks.

  • @tlf94949
    @tlf94949 ปีที่แล้ว

    Hello
    What about using concatenating with primitive instead of string object in your exemple

  • @ax8635
    @ax8635 ปีที่แล้ว

    Great to see live memory usages for those examples.

  • @JorgetePanete
    @JorgetePanete ปีที่แล้ว +1

    It's important to know how in Java 9 or 10 (idk) the bytecode changes, if you do several + to form a full string, like a text block without text block syntax, it's performant

    • @orbyfied
      @orbyfied ปีที่แล้ว +2

      isnt that just the compiler making it into a constant at compile time
      the compiler knows when you do `"a" + "b"` that it will always result in "ab"

  • @G-33k
    @G-33k ปีที่แล้ว +5

    Wa alaykom salam brother Amigo, nice informations as usual

  • @iluvsyphonfilter
    @iluvsyphonfilter ปีที่แล้ว

    I didn't know these differences, thanks for the tip!

  • @albaniaiptv8335
    @albaniaiptv8335 ปีที่แล้ว

    im android developer , and i use + or += but when the app is compiled , in the byte code it shows stringbuilder .

  • @ЗінаїдаПетрівна-в1ф
    @ЗінаїдаПетрівна-в1ф ปีที่แล้ว

    Thanks,
    What about String.concat() or stream(). ... . joining() ?

  • @Mykyta-y3k
    @Mykyta-y3k ปีที่แล้ว +2

    Hello. Thanks for usefull video.
    Can anyone explain WHY "slow method" (by creating new String variable) is slower than "fast method"(by using .addend of StringBuilder)? Is it bcause of number of operations for creation of new variable?

    • @LOLdjrabaanLOL
      @LOLdjrabaanLOL ปีที่แล้ว +4

      every addition to string creates a new string, and a string is a object stored in java memory, which needs to be created and managed. as you can imagine instaciating milion objects is expensive

    • @ampo287
      @ampo287 ปีที่แล้ว

      ​@@LOLdjrabaanLOL in addition, when it create millon length long string. it will takes so many memories to allocate it.

    • @youssefbouchara1179
      @youssefbouchara1179 ปีที่แล้ว

      Strings are immutable so you can't just add a star to an existing one.. StringBuilders in the other hand are mutable so you can just change them

  • @manikantareddy7595
    @manikantareddy7595 ปีที่แล้ว +1

    Slightly confused now, why isn't there an invoke dynamic call that appends these million to a StringBuilder and finally unwrap to String

    • @simonfarre4907
      @simonfarre4907 ปีที่แล้ว +2

      Because optimizers, regardless of the language, can only do so much heavy lifting for you. In the end, you have to be smart enough to not do things like this. Don't get me wrong, compilers and optimizers are fantastic, and they can optimize code in *amazing ways* but most people would be surprised with how fast an optimizer gets to a point where it can not guarantee a specific thing and therefore have to skip optimizing it entirely.

    • @manikantareddy7595
      @manikantareddy7595 ปีที่แล้ว

      @@simonfarre4907 thanks for the reply, but wouldn't it be cool if compiler works for human and not the other way around 😉

  • @tiennguyennhu5604
    @tiennguyennhu5604 ปีที่แล้ว

    Is that IntelliJ IDEA or how to config that like yours?

  • @dimmetrious
    @dimmetrious ปีที่แล้ว +1

    Good video. could you please name plugin for that big 'run\debug' at the top?

    • @amigoscode
      @amigoscode  ปีที่แล้ว +1

      New intellij theme

  • @kchemutai3483
    @kchemutai3483 ปีที่แล้ว

    Thank you so much @AmigisCode, this was eye opening

  • @dmitrik4610
    @dmitrik4610 ปีที่แล้ว

    Hello. Your test is not representative. When you build string with plus symbol java create new object and add it into string pool on each iteration. you used only 1 symbol at fast implementation and collect 1m links in string builder

  • @harshrajpal1828
    @harshrajpal1828 ปีที่แล้ว

    Bro which video editing tool you are using ?

  • @Ram-ly6hb
    @Ram-ly6hb ปีที่แล้ว

    Which IDE are you using?

  • @iZakirSheikh
    @iZakirSheikh ปีที่แล้ว

    What the name of theme that you r using for intellij idea

  • @حامدنیکبخت-ن5ع
    @حامدنیکبخت-ن5ع ปีที่แล้ว

    hi , How to create an anti optimally inside the loop?

  • @bilos125
    @bilos125 9 หลายเดือนก่อน

    How did it auto complete when he wrote sout?

  • @RiesenpiIz
    @RiesenpiIz ปีที่แล้ว

    Which ide are you using?

  • @doquocviet-sept3rd
    @doquocviet-sept3rd ปีที่แล้ว

    StringBuffer can be used in this case but it different with StringBuilder is synchronize and non-synchronize. =))

  • @anothermouth7077
    @anothermouth7077 ปีที่แล้ว

    Although Sonar suggest to use + instead of append

  • @vishwa4827
    @vishwa4827 ปีที่แล้ว +3

    Can anyone tell me the road map to learn java as a beginner

    • @ChandlerBing11
      @ChandlerBing11 ปีที่แล้ว

      Primitive types, String, OOP, Collections, Stream, Optional, Lambda and JDBC.

    • @ascar66
      @ascar66 ปีที่แล้ว

      ask google. There is a plethora of road maps

    • @DevToolsMadeSimple
      @DevToolsMadeSimple ปีที่แล้ว

      You can find it here: www.geeksforgeeks.org/java-developer-learning-path-a-complete-roadmap/

    • @vishwa4827
      @vishwa4827 ปีที่แล้ว

      @@ChandlerBing11i don't know what is stream and optional

    • @vishwa4827
      @vishwa4827 ปีที่แล้ว

      @@ascar66 ok bro tq

  • @amorosofps
    @amorosofps ปีที่แล้ว

    what theme are you using in your ide bro?

  • @soniablanche5672
    @soniablanche5672 ปีที่แล้ว

    Doesn't java optimize string concatenation in loops by using StringBuilder? I know modern Javascript engines do, so I would assume Java does the same thing since it's a very common operation.

    • @KingstonFortune
      @KingstonFortune ปีที่แล้ว

      Yes Java does optimize string concatenation using StringBuilder even if you don’t explicitly use it. Under the hood Java would create a new StringBuilder object and use the append method and once done it converts it to a string by using the toString method. And yeah as you mentioned SB provides much better performance if you wona concatenate in a loop 😇

  • @hamednikbakht9708
    @hamednikbakht9708 ปีที่แล้ว

    how to add entity in loop?

  • @cloey_b
    @cloey_b ปีที่แล้ว

    WONDERFUL, my friend. Thanks for this really helpful video and for sharing valuable knowledge with us. Greetings from Argentina💟

  • @SouravBanik90
    @SouravBanik90 ปีที่แล้ว

    Recently i ran into this issue comparing deserialized json.

  • @rutvikrajpura7618
    @rutvikrajpura7618 ปีที่แล้ว

    Can you make more videos on Thread and threadpool.....🎉

  • @carmenbravo8606
    @carmenbravo8606 11 หลายเดือนก่อน

    This is a great explanation of this common mistake! Awesome

  • @mookayreet8518
    @mookayreet8518 ปีที่แล้ว

    I want to see an implementition of API key Authentication and management if possible please

  • @DIFIWIFILUPO
    @DIFIWIFILUPO ปีที่แล้ว

    Thank you, you explain so well! thank you brother

  • @AqibRime
    @AqibRime ปีที่แล้ว +1

    why your theme is more darker than mine in linux?

  • @ahmedal-sharabi5322
    @ahmedal-sharabi5322 ปีที่แล้ว

    Great video and thumbnails always cracks me up 😂

  • @djaiprix
    @djaiprix ปีที่แล้ว

    this are the things you learn if you wan to be java certify. lern it long a go. but the exam was to hard. did not passed.

  • @chang112x
    @chang112x ปีที่แล้ว

    WOW, this is a huge difference!

  • @ahmedbishree9429
    @ahmedbishree9429 ปีที่แล้ว

    Essalamo Aleykum brother, thanks for the excellent example, I d like to ask you about your Adidas shirt from where you got it and appreciate that for you

  • @Alan-rf3im
    @Alan-rf3im ปีที่แล้ว

    You are a good boy man. Thanks a lot.

  • @mdzaidsiddiqui4262
    @mdzaidsiddiqui4262 ปีที่แล้ว +1

    What is the ide you're using? Great video btw!

    • @IvanRandomDude
      @IvanRandomDude ปีที่แล้ว +1

      Intellij IDEA

    • @doubly_negative
      @doubly_negative ปีที่แล้ว +1

      Intellij IDE but with new UI enabled (which is in beta).

    • @ynl9296
      @ynl9296 ปีที่แล้ว

      How to download it😮

    • @doubly_negative
      @doubly_negative ปีที่แล้ว

      @@ynl9296 Either enable it through settings or search for certain plugin to enable new ui on google

    • @vicary__
      @vicary__ ปีที่แล้ว

      @@ynl9296 u have beta version in settings, just turn it on

  • @albertoazinar1209
    @albertoazinar1209 ปีที่แล้ว

    Great video!!!!!🎉

  • @macaroane
    @macaroane ปีที่แล้ว

    In what real world scenario you would append to a string for let's say 1000 times, not 1 mil? can't think of any

  • @Educationship
    @Educationship ปีที่แล้ว

    WOW! Very insightful.

  • @gabrieldragone
    @gabrieldragone ปีที่แล้ว

    Great video!

  • @phucle-cb1fl
    @phucle-cb1fl ปีที่แล้ว

    How about template for Intelij IDE bro 😊?

  • @MuhammadHamzaHassan
    @MuhammadHamzaHassan ปีที่แล้ว

    Any tutorial series on C++?

  • @АндрейШуньгин
    @АндрейШуньгин ปีที่แล้ว

    Thanks, mate!

  • @georgeshchennikov6423
    @georgeshchennikov6423 ปีที่แล้ว +2

    Yeah! I always use StringBuilder 😀

    • @omer_usta
      @omer_usta ปีที่แล้ว +3

      Using Always StringBuilder is also not suitable for all things. it's important to note that StringBuilder is not thread-safe, which means that it should not be used in a multithreaded environment without proper synchronization

    • @ynl9296
      @ynl9296 ปีที่แล้ว

      but I think it depends on your businesses logic

    • @georgeshchennikov6423
      @georgeshchennikov6423 ปีที่แล้ว

      @@omer_usta yes, of courses)

    • @georgeshchennikov6423
      @georgeshchennikov6423 ปีที่แล้ว

      @@ynl9296 yep

  • @LthiagoR
    @LthiagoR ปีที่แล้ว

    Beautiful video

  • @thirdstreetnorth
    @thirdstreetnorth ปีที่แล้ว

    Great video! One small comment - an empty string is not a null - regarding your comment during the video. cheers!

  • @georgivalkanov2377
    @georgivalkanov2377 ปีที่แล้ว

    Please give the same comparison but in Python.

  • @serowy00
    @serowy00 ปีที่แล้ว

    What is this intelij theme?

  • @techme6053
    @techme6053 ปีที่แล้ว

    Is laptop necessary for coding 😔

  • @hstivggfghyhgfg8359
    @hstivggfghyhgfg8359 ปีที่แล้ว

    String is just a fixed size array of bytes

  • @mdabdurrakib6965
    @mdabdurrakib6965 ปีที่แล้ว

    Thank you so much

  • @XNEP1
    @XNEP1 ปีที่แล้ว

    Why are you able to concatenate strings with the '+' operator. This is so dumb.

  • @sbks7273
    @sbks7273 ปีที่แล้ว

    @2:00 I see what you did there :3

  • @LehmannMr
    @LehmannMr ปีที่แล้ว

    I personally prefer using + concatenation because of its readability. How often do you have such huge concatenations ?
    1.000,000 = 22 sec means even 1000 concatenations will take = 0,02 sec

  • @alekha007
    @alekha007 ปีที่แล้ว

    Basically, awesome 👏🏻 😃

  • @hemant8223
    @hemant8223 ปีที่แล้ว

    It's really great video.

  • @vladimirnechiporyuk2948
    @vladimirnechiporyuk2948 ปีที่แล้ว

    Thanks a lot.

  • @networkingknowledge6261
    @networkingknowledge6261 ปีที่แล้ว

    good to know , thx

  • @sohpol
    @sohpol ปีที่แล้ว

    F*ck me. I didn't expect this amount of slowness.

  • @raidenluikang5532
    @raidenluikang5532 ปีที่แล้ว

    Java String s always not intuitive for developers of other languages:
    1. String may be null and may be empty
    2. String contents compared with equals() method, not with == operator
    3. null String added to other string as "null" :)
    4. String + Integer --> String : "75" + 6 -> "756", Hi from JavaScript.
    5. String non mutable, for mutable operations always use StringBuilder
    6. Java Strings may be globally cached
    7. Doe not have operator [] for access to elements by index, welcome charAt
    ... And more ..

  • @mrMarseleene
    @mrMarseleene ปีที่แล้ว

    I knew about string and for concat use stringbuilder, but concat with null was mind blowing, i didn't even expect. Great job! more videos about java "underwear". Inshallah

  • @plinplinplonn
    @plinplinplonn ปีที่แล้ว

    Why is his intelijidea looking that dope

  • @abelmengesha3773
    @abelmengesha3773 ปีที่แล้ว

    Imagine being amigos colleague

  • @aayush5474
    @aayush5474 ปีที่แล้ว

    Java peeps decided to discard operator overloading but kept it in case of Strings meh

  • @diamantbrandy
    @diamantbrandy ปีที่แล้ว

    oh thanks

  • @elrolo6858
    @elrolo6858 ปีที่แล้ว

    I just realized I know nothing.
    Thanks amigo

  • @asatbekxalimjonov4005
    @asatbekxalimjonov4005 ปีที่แล้ว

    useful video

  • @valkokk
    @valkokk ปีที่แล้ว

    A title (and speech) is also part of the video, and I don't feel included in this issue... Don't use "You've been doing it wrong" and not all of us do it like you show it... Instead use "Some of you ..." ... because, you know, some of us also know how to code correctly, and even so, we like to come here.

  • @RiorXD
    @RiorXD ปีที่แล้ว

    died laughing at a and then null

  • @markross89
    @markross89 ปีที่แล้ว

    This is a cool topic, but it's rather basic knowladge. I'm not surprised people don't know this small things, I was the same after my Java bootcamp. Trust me it is worth to get back to basic things and master them properly as it is speeding your work. I'm studing with Oracle OCA studie book that was not recomended by my bootcamp teachers. It explaines all small things like this topic. Even if you dont want to get oracle certification, this book (and this channel 😅) is great way to gain basic knowledge, and stop constantly looking on stackoverflow.

  • @rahff99
    @rahff99 ปีที่แล้ว

    great

  • @alimrad7760
    @alimrad7760 ปีที่แล้ว

    🎉🎉🎉

  • @nson22
    @nson22 ปีที่แล้ว

    🤯

  • @AvalancheGameArt
    @AvalancheGameArt ปีที่แล้ว

    Calling the java compiler a COMPILER is a crime. you compile to machine code, in java you translate unto a bytecode for the jvm. is not the same thing,

    • @omer_usta
      @omer_usta ปีที่แล้ว +5

      Actually compiler in here correct, the term "compiler" is a general term used for any software that translates source code written in one programming language into another language. If we were talking about typescript or similar languages which are converting them to another language , the correct verb/word should be "transcompiler".

  • @RustySilver-w1q
    @RustySilver-w1q ปีที่แล้ว

    But this example taken to real life is not necessary

  • @Roger-we3co
    @Roger-we3co ปีที่แล้ว

    Anull... lol

  • @assilbenchaaben2573
    @assilbenchaaben2573 ปีที่แล้ว

    The fact that you are using java is already wrong 😂

  • @YusufIbr
    @YusufIbr ปีที่แล้ว +1

    pertamax gan

  • @Damian-qu9us
    @Damian-qu9us ปีที่แล้ว

    good video but u say basically too much man

  • @umairasad3896
    @umairasad3896 ปีที่แล้ว

    Once again first one

  • @tommy--k
    @tommy--k ปีที่แล้ว

    Good stuff, thanks!