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
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
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!
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.
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.
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
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.
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.
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?
Please explain the advantages of LocalDataTime with java.util.Data or Calendar . why choose LocalDateTime i think Data or Calendar have some bugs , Right ?
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.
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 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)
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 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.
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
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?
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
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.
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
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.
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 😇
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
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
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
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 ..
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
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.
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.
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,
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".
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
yes, but using multithreading is very specific. Not all companies uses it.
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
Thanks Omer for the information 👍
Thanks Omer , Nice explanation
@@GFunkEra1992 there is no impact of multithreading for local vraibles
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!
What I most like on your videos is your sense of humor, making learning into a funny thing.
Nice work man!
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.
Great video... Thanks for making this video. Nobody tells these small things that make a big difference in production.
True
Its classic. Read Effective Java by Joshua Bloch. Item 63 about performance of string concatenation. And in general whole book is very good.
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.
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
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.
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.
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.
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?
I always use StringBuilder but you just said in the beginning that the compiler optimize it to use StringBuilder automatically, or that's different?
Please explain the advantages of LocalDataTime with java.util.Data or Calendar . why choose LocalDateTime i think Data or Calendar have some bugs , Right ?
Awesome learning! I could not imagine the performance impact!
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.
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
In systems which generate files, reports etc. for example ERP systems, appending string multiple times is pretty frequent functionality
@@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)
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.
@@simonfarre4907 your obviously haven't kept up with GC performance. ZGC runs full gcs in less than a millisecond with Tera bytes of heap
@@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.
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.
Hi, Amigo.
What's your IntelliJ theme that your folders and subfolders like that ?
Thanks.
same
Hello
What about using concatenating with primitive instead of string object in your exemple
Great to see live memory usages for those examples.
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
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"
Wa alaykom salam brother Amigo, nice informations as usual
I didn't know these differences, thanks for the tip!
im android developer , and i use + or += but when the app is compiled , in the byte code it shows stringbuilder .
Thanks,
What about String.concat() or stream(). ... . joining() ?
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?
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
@@LOLdjrabaanLOL in addition, when it create millon length long string. it will takes so many memories to allocate it.
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
Slightly confused now, why isn't there an invoke dynamic call that appends these million to a StringBuilder and finally unwrap to String
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.
@@simonfarre4907 thanks for the reply, but wouldn't it be cool if compiler works for human and not the other way around 😉
Is that IntelliJ IDEA or how to config that like yours?
Good video. could you please name plugin for that big 'run\debug' at the top?
New intellij theme
Thank you so much @AmigisCode, this was eye opening
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
Bro which video editing tool you are using ?
Which IDE are you using?
What the name of theme that you r using for intellij idea
hi , How to create an anti optimally inside the loop?
How did it auto complete when he wrote sout?
Which ide are you using?
StringBuffer can be used in this case but it different with StringBuilder is synchronize and non-synchronize. =))
Although Sonar suggest to use + instead of append
Can anyone tell me the road map to learn java as a beginner
Primitive types, String, OOP, Collections, Stream, Optional, Lambda and JDBC.
ask google. There is a plethora of road maps
You can find it here: www.geeksforgeeks.org/java-developer-learning-path-a-complete-roadmap/
@@ChandlerBing11i don't know what is stream and optional
@@ascar66 ok bro tq
what theme are you using in your ide bro?
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.
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 😇
how to add entity in loop?
WONDERFUL, my friend. Thanks for this really helpful video and for sharing valuable knowledge with us. Greetings from Argentina💟
Recently i ran into this issue comparing deserialized json.
Can you make more videos on Thread and threadpool.....🎉
This is a great explanation of this common mistake! Awesome
I want to see an implementition of API key Authentication and management if possible please
Thank you, you explain so well! thank you brother
why your theme is more darker than mine in linux?
same
Great video and thumbnails always cracks me up 😂
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.
WOW, this is a huge difference!
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
You are a good boy man. Thanks a lot.
What is the ide you're using? Great video btw!
Intellij IDEA
Intellij IDE but with new UI enabled (which is in beta).
How to download it😮
@@ynl9296 Either enable it through settings or search for certain plugin to enable new ui on google
@@ynl9296 u have beta version in settings, just turn it on
Great video!!!!!🎉
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
WOW! Very insightful.
Great video!
How about template for Intelij IDE bro 😊?
Any tutorial series on C++?
Thanks, mate!
Yeah! I always use StringBuilder 😀
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
but I think it depends on your businesses logic
@@omer_usta yes, of courses)
@@ynl9296 yep
Beautiful video
Great video! One small comment - an empty string is not a null - regarding your comment during the video. cheers!
Please give the same comparison but in Python.
What is this intelij theme?
same
Is laptop necessary for coding 😔
String is just a fixed size array of bytes
Thank you so much
Why are you able to concatenate strings with the '+' operator. This is so dumb.
@2:00 I see what you did there :3
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
Basically, awesome 👏🏻 😃
It's really great video.
Thanks a lot.
good to know , thx
F*ck me. I didn't expect this amount of slowness.
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 ..
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
Why is his intelijidea looking that dope
Imagine being amigos colleague
Java peeps decided to discard operator overloading but kept it in case of Strings meh
oh thanks
I just realized I know nothing.
Thanks amigo
useful video
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.
died laughing at a and then null
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.
great
🎉🎉🎉
🤯
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,
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".
But this example taken to real life is not necessary
Anull... lol
The fact that you are using java is already wrong 😂
pertamax gan
good video but u say basically too much man
Once again first one
Good stuff, thanks!