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

Поделиться
HTML-код
  • Опубликовано: 28 сен 2024

Комментарии • 155

  • @omer_usta
    @omer_usta Год назад +196

    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!

  • @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.

  • @gorandev
    @gorandev Год назад +5

    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.

  • @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.

  • @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.

  • @G-33k
    @G-33k Год назад +5

    Wa alaykom salam brother Amigo, nice informations as usual

  • @ax8635
    @ax8635 Год назад

    Great to see live memory usages for those examples.

  • @SouravBanik90
    @SouravBanik90 Год назад

    Recently i ran into this issue comparing deserialized json.

  • @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?

  • @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"

  • @video-markt
    @video-markt Год назад

    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.

  • @carmenbravo8606
    @carmenbravo8606 8 месяцев назад

    This is a great explanation of this common mistake! Awesome

  • @kchemutai3483
    @kchemutai3483 Год назад

    Thank you so much @AmigisCode, this was eye opening

  • @tlf94949
    @tlf94949 Год назад

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

  • @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.

  • @bilos125
    @bilos125 6 месяцев назад

    How did it auto complete when he wrote sout?

  • @code-discover
    @code-discover Год назад

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

  • @iZakirSheikh
    @iZakirSheikh Год назад

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

  • @rutvikrajpura7618
    @rutvikrajpura7618 Год назад

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

  • @Alan-rf3im
    @Alan-rf3im Год назад

    You are a good boy man. Thanks a lot.

  • @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 Год назад +1

      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 😉

  • @hstivggfghyhgfg8359
    @hstivggfghyhgfg8359 Год назад

    String is just a fixed size array of bytes

  • @Ram-ly6hb
    @Ram-ly6hb Год назад

    Which IDE are you using?

  • @albaniaiptv8335
    @albaniaiptv8335 Год назад

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

  • @RiesenpiIz
    @RiesenpiIz Год назад

    Which ide are you using?

  • @hamednikbakht9708
    @hamednikbakht9708 Год назад

    how to add entity in loop?

  • @dimmetrious
    @dimmetrious Год назад +1

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

  • @chang112x
    @chang112x Год назад

    WOW, this is a huge difference!

  • @DIFIWIFILUPO
    @DIFIWIFILUPO Год назад

    Thank you, you explain so well! thank you brother

  • @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?

  • @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

  • @frankmeneses5947
    @frankmeneses5947 Год назад

    Great video!

  • @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

  • @АндрейШуньгин
    @АндрейШуньгин Год назад

    Thanks, mate!

  • @حامدنیکبخت-ن5ع
    @حامدنیکبخت-ن5ع Год назад

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

  • @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

  • @tiennguyennhu5604
    @tiennguyennhu5604 Год назад

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

  • @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

  • @ЗінаїдаПетрівна-в1ф

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

  • @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 😇

  • @thirdstreetnorth
    @thirdstreetnorth Год назад

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

  • @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

  • @albertoazinar1209
    @albertoazinar1209 Год назад

    Great video!!!!!🎉

  • @sbks7273
    @sbks7273 Год назад

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

  • @abelmengesha3773
    @abelmengesha3773 Год назад

    Imagine being amigos colleague

  • @networkingknowledge6261
    @networkingknowledge6261 Год назад

    good to know , thx

  • @aayush5474
    @aayush5474 Год назад

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

  • @vladimirnechiporyuk2948
    @vladimirnechiporyuk2948 Год назад

    Thanks a lot.

  • @XNEP1
    @XNEP1 Год назад

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

  • @mdabdurrakib6965
    @mdabdurrakib6965 Год назад

    Thank you so much

  • @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

  • @diamantbrandy
    @diamantbrandy Год назад

    oh thanks

  • @phucle-cb1fl
    @phucle-cb1fl Год назад

    How about template for Intelij IDE bro 😊?

  • @techme6053
    @techme6053 Год назад

    Is laptop necessary for coding 😔

  • @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

  • @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 ..

  • @kasperserzysko1167
    @kasperserzysko1167 Год назад

    What is this intelij theme?

  • @rahff99
    @rahff99 Год назад

    great

  • @elrolo6858
    @elrolo6858 Год назад

    I just realized I know nothing.
    Thanks amigo

  • @asatbekxalimjonov4005
    @asatbekxalimjonov4005 Год назад

    useful video

  • @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

  • @Roger-we3co
    @Roger-we3co Год назад

    Anull... lol

  • @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.

  • @assilbenchaaben2573
    @assilbenchaaben2573 Год назад

    The fact that you are using java is already wrong 😂

  • @Damian-qu9us
    @Damian-qu9us Год назад

    good video but u say basically too much man

  • @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".

  • @YusufIbr
    @YusufIbr Год назад +1

    pertamax gan

  • @tommy--k
    @tommy--k Год назад

    Good stuff, thanks!

  • @GringoFlappy
    @GringoFlappy Год назад

    Hmm you started interesting😅 A + null makes…. Ok I am sorry🥲

  • @rpdemo
    @rpdemo Год назад +10

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

  • @vanoanhpham2861
    @vanoanhpham2861 Год назад +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 ?

  • @aryangholamlou
    @aryangholamlou Год назад +2

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

  • @AqibRime
    @AqibRime Год назад +1

    why your theme is more darker than mine in linux?

  • @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?

  • @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

  • @sohpol
    @sohpol Год назад

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

  • @plinplinplonn
    @plinplinplonn Год назад

    Why is his intelijidea looking that dope

  • @harshrajpal1828
    @harshrajpal1828 Год назад

    Bro which video editing tool you are using ?

  • @MuhammadHamzaHassan
    @MuhammadHamzaHassan Год назад

    Any tutorial series on C++?

  • @LthiagoR
    @LthiagoR Год назад

    Beautiful video

  • @nson22
    @nson22 Год назад

    🤯

  • @RustySilver-w1q
    @RustySilver-w1q Год назад

    But this example taken to real life is not necessary

  • @cloey_b
    @cloey_b Год назад

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

  • @mookayreet8518
    @mookayreet8518 Год назад

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

  • @georgivalkanov2377
    @georgivalkanov2377 Год назад

    Please give the same comparison but in Python.

  • @anothermouth7077
    @anothermouth7077 Год назад

    Although Sonar suggest to use + instead of append

  • @iluvsyphonfilter
    @iluvsyphonfilter Год назад

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

  • @Educationship
    @Educationship Год назад

    WOW! Very insightful.

  • @alekha007
    @alekha007 Год назад

    Basically, awesome 👏🏻 😃

  • @ahmedal-sharabi5322
    @ahmedal-sharabi5322 Год назад

    Great video and thumbnails always cracks me up 😂

  • @hemant8223
    @hemant8223 Год назад

    It's really great video.

  • @gabrielalvesgoncalves9959
    @gabrielalvesgoncalves9959 Год назад

    Great video!