This week's book giveaway is in the JDBC and Relational Databases forum.
We're giving away four copies of Murach's MySQL and have Joel Murach on-line!
See this thread for details.
Win a copy of Murach's MySQL this week in the JDBC and Relational Databases forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

how can we optimize the following code (interviewer asked)

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
code 1


code 2:


please your comments?
 
Saloon Keeper
Posts: 10639
83
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Pulak, welcome to The Ranch!

When posting code here please UseCodeTags (<---a link for you to read). I fixed it for you this time.
 
Bartender
Posts: 5464
212
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
yes, welcome to the Ranch!

Did that interviewer tell you in what way the code should be optimized?
 
Marshal
Posts: 79016
375
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What makes your interviewer think there is a performance problem with that sort of code?
Did you tell them off for using a loop to print out an array of arrays?
 
pulak dhar
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
for code 1:  i have given following lamda with stream solution but he was not satisfied with my answer

Arrays.stream(sum).forEach(x-> Arrays.stream(x).forEach( y -> System.out.println(y)));

 
Piet Souris
Bartender
Posts: 5464
212
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Your lambda results in one large column. Was there something wrong with that for- loop?
 
Marshal
Posts: 4468
567
VSCode Eclipse IDE TypeScript Redhat MicroProfile Quarkus Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Piet Souris wrote:yes, welcome to the Ranch!

Did that interviewer tell you in what way the code should be optimized?


That would be my first question as well - optimized for what: performance, readability, code size, etc.?
 
pulak dhar
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
his question was how to optimize this code snippet. Is there any possibilities to optimize apart from system.out.println?

 
Marshal
Posts: 28127
94
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You could print the result as you compute the sum of the arrays, instead of storing the sum and then printing it later.

That at least reduces the size of the code. Whether it reduces the running time, it might do that a bit but the vast majority of the running time would be in the printing part. It would reduce the memory usage, but those arrays are trivially small anyway.
 
Master Rancher
Posts: 4757
71
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think you need to consider the possibility that the interviewer knows less about performance optimization than they think they do.  It happens.

Now, phrasing it that way may not be the best way to respond in an interview where you actually want the job.  In that case, asking more questions is probably the most productive response - the questions asked in this thread by the other respondents are a good example.
 
Campbell Ritchie
Marshal
Posts: 79016
375
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Piet Souris wrote:. . . Was there something wrong with that for- loop?

Nothing that can't be cured with the followjng (it's in Jave Puzzlers by Bloch and Gafter):-
 
Campbell Ritchie
Marshal
Posts: 79016
375
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Mike Simmons wrote:. . . the interviewer knows less about performance optimization than they think they do. . . . .

Mike, you don't say!
 
Campbell Ritchie
Marshal
Posts: 79016
375
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Paul Clapham wrote:. . . the vast majority of the running time would be in the printing part. . . . .

If it takes 1ms for each println() call, that is probably 10,000× longer (each call) than the whole of the remainder of the program. So using Arrays.deepToString() will probably be the one thing that will speed up execution. And I bet MS is ight and the interviewer doesn't know anything about it.
 
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Mike Simmons wrote:I think you need to consider the possibility that the interviewer knows less about performance optimization than they think they do.  It happens.


First rule of optimization: Don't do it!
Second rule of optimization (for experts only!): Don't do it yet!

Also, programmers are notoriously bad at optimizing using gut feeling and intuition. A good extension to that is probably that interviewers who ask candidates to optimize code are worse.
 
Paul Clapham
Marshal
Posts: 28127
94
Eclipse IDE Firefox Browser MySQL Database
  • Likes 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
We haven't discussed Code 2 yet:

 
Campbell Ritchie
Marshal
Posts: 79016
375
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
No, we haven't discussed it. I don't think I noticed it poperly. But is your suggestion an optimisation or a different program altogether? You can speed up execution by getting rid of the recursion, or by using the formulaa I learnt about the age of 13:-
 
Campbell Ritchie
Marshal
Posts: 79016
375
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you change 20 to 40_000 in line 4, you get a different output
 
Piet Souris
Bartender
Posts: 5464
212
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
We still don't know what has to be done. Add a test for addNumbers(-3)? Prevent SOEs? Use only lambdas? Use helper-methods?
 
Paul Clapham
Marshal
Posts: 28127
94
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:But is your suggestion an optimisation or a different program altogether?



That's a very difficult question.
 
Campbell Ritchie
Marshal
Posts: 79016
375
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Piet Souris wrote:. . . . Add a test for addNumbers(-3)? Prevent SOEs? Use only lambdas? Use helper-methods?

Shoot the interviewer? Nothing at all? I would say that the only optimisation worth considering is avoiding multiple print statements. I would say the other code will run so fast for an argument of 20 that you aren't going to notice any other optimisation.
 
Saloon Keeper
Posts: 27694
196
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
How would I optimize it?

First, measure it. Find out what resources it uses and where. Don't EVER optimize based on what you "know" the problem is. I've spent a long and evil career where much of what I did required high efficiency and/or reliability and the problems were almost never even remotely related to where everyone (including me!) "knew" they'd be. And, incidentally, replacing the whole algorithm is frequently the best solution. Do you have time to do that during an interview?

Secondly, does it even need optimization? Does it run often enough to make a difference? What exactly are the resources that are being (in their opinion) being over-consumed. Your solution — if any — will depend very much on whether it's RAM, CPU, I/O, paging, network bandwidth or something else. Obviously for this specific case, stuff like network bandwidth isn't likely to apply, but that's part of what you must discover.

This sort of question reminds me of an interview I did a couple of years back where candidates had to take an exam to qualify. They asked for "the" solution for a situation that I could have provided no less than 5 approaches just off the top of my head. They were testing for ignorance as much as they were testing for knowledge.
 
Marshal
Posts: 8834
631
Mac OS X VI Editor BSD Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If the code you showed in your first post was an exercise snippet, then I personally would start by decomposing it and removing noise, i.e. useless comments, and fixing formatting.

Something along the lines:

Now you have some names attached to the code which you can use to discuss with an interviewer and ask, which part(s) of the code they are referring to to be optimised, and apparently in which way?

There are some problems potentially in method addMatrices() method (interviewer's and this version).
 
Campbell Ritchie
Marshal
Posts: 79016
375
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Paul Clapham wrote:. . . That's a very difficult question.

Afraid I disagree. Because the adding method is public, removing it and calculating the result outwith the progam will make that method unavailable to other code, and that changes the semantics of the whole program. If you replace the original class with yours, you might even get one of these!
 
Campbell Ritchie
Marshal
Posts: 79016
375
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Let's try Arrays#deepToString()

Campbell's JShell wrote:jshell> int[][] matrix = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}};
  ...>        
  ...>        
matrix ==> int[3][] { int[3] { 0, 1, 2 }, int[3] { 3, 4, 5 }, int[3] { 6, 7, 8 } }

jshell> Arrays.deepToString(matrix)
$2 ==> "[[0, 1, 2], [3, 4, 5], [6, 7, 8]]"

Piet is right; the formatting is very iffy.
[edit]Spellling corrections
 
Mike Simmons
Master Rancher
Posts: 4757
71
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Interestingly, the original addNumbers() method actually is worth optimizing -- or at least, refactoring to a simpler and more readable form, which will incidentally also be more performant, in all likelihood.  This could actually be a worthwhile interview question.  But we've kind of skipped around that part of the discussion.

For the original poster:  consider this code only:

Various questions could be asked about it:

What does it do?
What other way(s) could you write a method that does the same thing?  
Can you make it easier to understand?  
Do you see any problems with how this method is implemented?  Any improvements you could make?
Are there any inputs which would cause problems for this method?  How could you code the method differently to handle those problems?
Can you make it faster?

The last question seems less useful to me than the others.  But still, yes there are several ways to make this method faster, if that's really needed.  And several ways to make it better, in other ways.

Similar questions could be asked about code 1 as well.  The main difference is that code 1 doesn't really have useful performance optimizations to perform, while code 2 does.  But they both have other improvements that could be made, to make the code more reliable.
 
Liutauras Vilda
Marshal
Posts: 8834
631
Mac OS X VI Editor BSD Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Mike Simmons wrote:Interestingly, the original addNumbers() method actually is worth optimizing -- or at least, refactoring to a simpler and more readable form, which will incidentally also be more performant, in all likelihood.


First of all - it is buggy. But I agree, that reworking it to be simpler, by proxy would eliminate the bug as well.

Campbell's solution is tempting, but not immune to potential problems as well I think.
 
Liutauras Vilda
Marshal
Posts: 8834
631
Mac OS X VI Editor BSD Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


Probably it doesn't bother a lot of people, but method name does not make sense as well.


Having this name, I'd expect it to be:

and maybe
 
Campbell Ritchie
Marshal
Posts: 79016
375
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Mike Simmons wrote:. . . a worthwhile interview question.  But we've kind of skipped around that part of the discussion. . . . .

That is because we are concentrating (or maybe even perseverating) on the question asked in the interview.
 
Campbell Ritchie
Marshal
Posts: 79016
375
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
My formula, as above, or as (n² − n) ÷ 2, will give the correct result for the arguments supplied; it will give incorrect answers for negative arguments or those large enough to cause an overflow error. But the OP was asked to optimise the code, not to correct it. Maybe the original version is “less incorrect;” at least it will throw an exception before it suffers an overflow error. That latter isn't guaranteed; when I buy a computer with 16TB of RAM, that will provide enough stack space capacity to permit an overflow error to pass unnoticed.
* * * * * * * * * * * * * * * * * *
Is that an error in Java®'s design that it is the one C‑based language not to support signed and unsigned ints? Or would the problem still occur with unsigned ints? I think it probably would.
 
Campbell Ritchie
Marshal
Posts: 79016
375
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Yesterrday, I wrote:. . . (n² − n) ÷ 2 . . . .

. . . and Piet Souris pointed out that should read (n² + n) ÷ 2
 
I'm not dead! I feel happy! I'd like to go for a walk! I'll even read a tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic