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

  Рет қаралды 91,782

Amigoscode

Amigoscode

Күн бұрын

Пікірлер: 155
@omer_usta
@omer_usta Жыл бұрын
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 Жыл бұрын
yes, but using multithreading is very specific. Not all companies uses it.
@RobertSaulnier
@RobertSaulnier Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
What I most like on your videos is your sense of humor, making learning into a funny thing. Nice work man!
@gorandev
@gorandev Жыл бұрын
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 Жыл бұрын
Great video... Thanks for making this video. Nobody tells these small things that make a big difference in production.
@DevToolsMadeSimple
@DevToolsMadeSimple Жыл бұрын
True
@z00lus
@z00lus Жыл бұрын
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 Жыл бұрын
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.
@CottidaeSEA
@CottidaeSEA Жыл бұрын
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.
@bkaaron3728
@bkaaron3728 Жыл бұрын
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
@hardikpanchal9726
@hardikpanchal9726 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
Hi, Amigo. What's your IntelliJ theme that your folders and subfolders like that ? Thanks.
@joaoruss0
@joaoruss0 Жыл бұрын
same
@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 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
Wa alaykom salam brother Amigo, nice informations as usual
@albaniaiptv8335
@albaniaiptv8335 Жыл бұрын
im android developer , and i use + or += but when the app is compiled , in the byte code it shows stringbuilder .
@iluvsyphonfilter
@iluvsyphonfilter Жыл бұрын
I didn't know these differences, thanks for the tip!
@ЗінаїдаПетрівна-в1ф
@ЗінаїдаПетрівна-в1ф Жыл бұрын
Thanks, What about String.concat() or stream(). ... . joining() ?
@Mykyta-y3k
@Mykyta-y3k Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
Good video. could you please name plugin for that big 'run\debug' at the top?
@amigoscode
@amigoscode Жыл бұрын
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 Жыл бұрын
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?
@hamednikbakht9708
@hamednikbakht9708 Жыл бұрын
how to add entity in loop?
@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 😇
@cloey_b
@cloey_b Жыл бұрын
WONDERFUL, my friend. Thanks for this really helpful video and for sharing valuable knowledge with us. Greetings from Argentina💟
@rutvikrajpura7618
@rutvikrajpura7618 Жыл бұрын
Can you make more videos on Thread and threadpool.....🎉
@SouravBanik90
@SouravBanik90 Жыл бұрын
Recently i ran into this issue comparing deserialized json.
@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 Жыл бұрын
why your theme is more darker than mine in linux?
@joaoruss0
@joaoruss0 Жыл бұрын
same
@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 Жыл бұрын
What is the ide you're using? Great video btw!
@IvanRandomDude
@IvanRandomDude Жыл бұрын
Intellij IDEA
@doubly_negative
@doubly_negative Жыл бұрын
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 Жыл бұрын
Yeah! I always use StringBuilder 😀
@omer_usta
@omer_usta Жыл бұрын
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?
@joaoruss0
@joaoruss0 Жыл бұрын
same
@techme6053
@techme6053 Жыл бұрын
Is laptop necessary for coding 😔
@hstivggfghyhgfg8359
@hstivggfghyhgfg8359 Жыл бұрын
String is just a fixed size array of bytes
@XNEP1
@XNEP1 Жыл бұрын
Why are you able to concatenate strings with the '+' operator. This is so dumb.
@mdabdurrakib6965
@mdabdurrakib6965 Жыл бұрын
Thank you so much
@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 Жыл бұрын
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 Жыл бұрын
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!
10 Most Common Java Developer Mistakes
16:13
Amigoscode
Рет қаралды 112 М.
NEVER Write This Line Of Code In Production. Seriously
13:21
Amigoscode
Рет қаралды 59 М.
So Cute 🥰 who is better?
00:15
dednahype
Рет қаралды 19 МЛН
We Attempted The Impossible 😱
00:54
Topper Guild
Рет қаралды 56 МЛН
Quilt Challenge, No Skills, Just Luck#Funnyfamily #Partygames #Funny
00:32
Family Games Media
Рет қаралды 55 МЛН
Правильный подход к детям
00:18
Beatrise
Рет қаралды 11 МЛН
Premature Optimization
12:39
CodeAesthetic
Рет қаралды 842 М.
Better Java Streams with Gatherers - JEP Cafe #23
1:13:32
How Senior Programmers ACTUALLY Write Code
13:37
Thriving Technologist
Рет қаралды 1,6 МЛН
Learn How to Use Abstract Classes
17:28
Amigoscode
Рет қаралды 68 М.
Solving one of PostgreSQL's biggest weaknesses.
17:12
Dreams of Code
Рет қаралды 220 М.
Learn Dependency Injection and Write Better Code
21:52
Amigoscode
Рет қаралды 177 М.
My 10 “Clean” Code Principles (Start These Now)
15:12
Conner Ardman
Рет қаралды 305 М.
10 Spring and Spring Boot Common Mistakes You Need To STOP
15:49
Amigoscode
Рет қаралды 160 М.
So Cute 🥰 who is better?
00:15
dednahype
Рет қаралды 19 МЛН