简体   繁体   English

如何为每个循环优化嵌套

[英]How to optimize nested for each loops

I wanted to optimize the below code.我想优化下面的代码。 Will streams optimize the below nested foreach loops?流会优化下面嵌套的 foreach 循环吗? If so am new to streams can someone please help me?如果是这样,我是流的新手,有人可以帮助我吗? In the below I have replaced the names for project confidentiality purpose.在下面,出于项目保密目的,我替换了名称。 Shall be using the tList for further processing in the code.应使用 tList 在代码中进行进一步处理。 Can some one please help on this?有人可以帮忙吗?

List<Tea> tea = requestBody.getTea();
            
for (Tea tea1 : teas) {
    List<String> teaValues = tea1.getTeaValues();
    for (String t : teaValues) {
        if ((t).contains("tMapping") || ((t).contains("tdata"))) {
            int subStrng = t.indexOf(".") + 1;
            int subStrngSpace = t.indexOf(" ");
            String tStrng = t.substring(subStrng, subStrngSpace);
            tList.add(tStrng);
        } else {
            String[] tStrng = t.split("\'");
                String t1 = tStrng[1];
                tList.add(t1);
            
        }
    }
}

Will streams optimize the below nested foreach loops?流会优化下面嵌套的 foreach 循环吗?

No, not really.不,不是真的。 Unless you have a really big input and you're using a server with multiple processes/cores, then you can get a speed up from using parallel streams .除非您有非常大的输入并且您使用的是具有多个进程/核心的服务器,否则您可以通过使用并行流来提高速度。

Otherwise, these streams will just be converted into loops "under the hood" ...否则,这些流将被转换为“幕后”循环......

This is to answer your question.这是为了回答你的问题。

Now let's look at the question behind the question ... why do you want to optimise it ?现在我们来看看问题背后的问题……为什么要优化它? How will you know that your optimisation level is good enough ?你怎么知道你的优化级别足够好?

EDIT:编辑:

  1. If this is to be designed to handle super big inputs you need to make use of concurrency.如果这是为了处理超大输入而设计的,您需要利用并发性。 The easiest way to do it would be to use parallel streams.最简单的方法是使用并行流。
  2. Even better would be to move this processing code from the application into the database.更好的是将这个处理代码从应用程序移到数据库中。 It will be able to process this even faster.它将能够更快地处理这个问题。 Just write a native query (see here ) which does all the transforms of data within the database.只需编写一个本机查询(请参阅此处),它会执行数据库中的所有数据转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM